开发者

Issue with: "Warning: Invalid argument supplied for foreach"

开发者 https://www.devze.com 2023-03-09 17:08 出处:网络
I\'m having some woes with the above stated warning on an array. I completely understand what the warning is, and what causes it, and I have taken every step I can to prevent it, but alas, none are h

I'm having some woes with the above stated warning on an array.

I completely understand what the warning is, and what causes it, and I have taken every step I can to prevent it, but alas, none are having any effect.

Steps taken:

I have Checked for the array, declared it if not exists.

if(!$this->theVariables['associated']){
    $this->theVariables['associated'] = array();
   }

and

$this->theVariables['associated'] = $this->theVariables['associated'] || array();

Neither have any effect.

I have wrapped the foreach in an if that checks the array is not empty (!empty()), that it exists, that it is an array (is_array()), and then even type cast the array in the foreach declaration (foreach((array)$this->theVariables['associated'] as $item)) yet I am still getting this Warning.

As I have no way of switching error reporting off on this specific server, is there no other way of stopping this warning from displaying?

It is driving开发者_如何学Python me nuts.


try:

if (is_array($this->theVariables['associated'])) {
  // your foreach here
}

bacause for example if

$this->theVariables['associated'] would be 1 this array assignment would never be reached:

if(!$this->theVariables['associated']){
    $this->theVariables['associated'] = array();
}

(The same goes for your second test)

As for Ólafur Waages comment, have a look at Lazy evaluation.

For example, if your test looked something like this, you'll probably get problems:

<?php
$fakeArray = 'bad';

if (empty($fakeArray) && !is_array($fakeArray)) {
    $fakeArray = array();
}

var_dump($fakeArray);

Output:

string(3) "bad"


Why just didn't check with if (is_array($this->theVariables['associated'])){?


If you really need to loop through that object, cast it as an array first:

foreach((array) $this->theVariable as $key => $value){
     echo $key . " = " . $value . "<br>";
 }


if (!$this->theVariables['associated'])

is not checking whether the array exists.

Write this instead:

if (!isset($this->theVariables['associated']) ||
   !is_array($this->theVariables['associated']))
0

精彩评论

暂无评论...
验证码 换一张
取 消