designermonkey
designermonkey

Reputation: 1108

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

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 me nuts.

Upvotes: 0

Views: 442

Answers (4)

Yoshi
Yoshi

Reputation: 54649

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"

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

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

is not checking whether the array exists.

Write this instead:

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

Upvotes: 0

Stephane Gosselin
Stephane Gosselin

Reputation: 9148

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>";
 }

Upvotes: 0

RRStoyanov
RRStoyanov

Reputation: 1172

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

Upvotes: 0

Related Questions