Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP @ foreach warning

Tags:

php

I have a PHP foreach from an array, the array is given to me by my DB provider via a soap web service so I cannot change the array I get. When there are no elements to return, I get an empty array, this results in

Warning: Invalid argument supplied for foreach()

the loop looks like

foreach (($point1['return']) as $val) 

Where can I put an @ to stop this warning, and if I cant, what I do I do to turn off php warnings.

like image 646
David Avatar asked Nov 07 '11 10:11

David


People also ask

How do you fix warning Invalid argument supplied for foreach?

Cast the variable into an array Sometimes, the “invalid argument supplied for foreach() ” warning still appears when you pass a multi-dimensional array. Using the isset and array casting as shown above will help you resolve the warning for multi-dimensional arrays.

What is foreach () in PHP?

What is foreach in PHP? The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.

Why Is Invalid argument supplied for foreach?

The "invalid argument supplied for foreach() " error​ occurs when PHP's built-in foreach() tries to iterate over a data structure that is not recognized as an array or object.

Does foreach mutate array?

forEach() does not mutate the array on which it is called, but the function provided as callbackFn can.


2 Answers

Hiding the warning is not the right way. You should check whether it exists and is an array.

if (is_array($point1['return'])) {
    foreach ($point1['return'] as $val)  {
         ...
    }
}

PHP is_array()

Actually, turning off warnings or using the @ operator is not the right way to go 99% of the time.

Solve the problem instead of hiding it.

like image 83
kapa Avatar answered Nov 11 '22 14:11

kapa


foreach() can handle not only arrays but also objects by either using the the default "all visible properties" implementation or a custom implementation via the traversable/iterator interface.
And a "DB provider via a soap web service" is something where I'd keep an eye on the possibility of (suddenly) having an object/iterator instead of a plain array.
So, if you're going to test the existence and data type before passing the variable to foreach, you should consider not only testing for is_array() but also for instanceof Traversable.

<?php
class Foo implements Iterator {
    protected $v = 0;
    public function current() { return $this->v; }
    public function key() { return $this->v; }
    public function next() { ++$this->v; }
    public function rewind() { $this->v=0; }
    public function valid() { return 10>$this->v; }
}

//$a = array(1,2,3,4);
$a = new Foo;


if( is_array($a) || $a instanceof Traversable ) {
    foreach($a as $e) {
        echo $e, "\n";
    }
}
like image 7
VolkerK Avatar answered Nov 11 '22 12:11

VolkerK