Invalid argument supplied for foreach() Invalid argument supplied for foreach() php php

Invalid argument supplied for foreach()


Personally I find this to be the most clean - not sure if it's the most efficient, mind!

if (is_array($values) || is_object($values)){    foreach ($values as $value)    {        ...    }}

The reason for my preference is it doesn't allocate an empty array when you've got nothing to begin with anyway.


How about this one? lot cleaner and all in single line.

foreach ((array) $items as $item) { // ... }


I usually use a construct similar to this:

/** * Determine if a variable is iterable. i.e. can be used to loop over. * * @return bool */function is_iterable($var){    return $var !== null         && (is_array($var)             || $var instanceof Traversable             || $var instanceof Iterator             || $var instanceof IteratorAggregate            );}$values = get_values();if (is_iterable($values)){    foreach ($values as $value)    {        // do stuff...    }}

Note that this particular version is not tested, its typed directly into SO from memory.

Edit: added Traversable check