PHP warning @foreach

I have PHP foreach from an array, the array is provided to me by the database provider through a soapy web service, so I cannot modify the resulting array. When there are no items to return, I get an empty array, this leads to

Warning: Invalid argument supplied for foreach() 

the cycle looks like

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

Where can I put @ to stop this warning, and if I cannot, what am I doing, I am doing it to disable php warnings.

+6
source share
7 answers

Hiding the warning is the wrong way. You should check if it exists and is an array.

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

PHP is_array ()

In fact, turning off alerts or using the @ operator is the wrong way to jump in 99% of cases.

Solve the problem, not hide it.

+16
source

An empty array does not cause this error, the problem is that you are trying to iterate through something that is not an array. You can add validation using is_array .

+4
source

foreach () can process not only arrays , but also objects by using the default implementation of "all visible properties" or a custom implementation using traversable / iterator .
And β€œa database provider through a soapy web service” is that I will monitor the possibility of (suddenly) having an object / iterator instead of a simple array.
So, if you are going to check the existence and data type before passing the variable to foreach, you should consider not only testing 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"; } } 
+4
source

Check the array first:

 if(is_array($point1['return'])) { ... } 
+2
source

It is better to allow errors to be displayed, but first check that the input is an array. This way you can wrap foreach in if, for example:

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

You can also explicitly pass an argument to an array:

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

Note: this will still produce an undefined index if in $point1

no key "return",
+2
source

Check if this is an array. with is_array(); !! There is no need to suppress the warning. In fact, it is impossible to prevent this warning about an invalid argument.

+1
source

Source: https://habr.com/ru/post/900924/


All Articles