Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Invalid argument supplied for foreach() in PHP Language ?

$values = get_values();

foreach ($values as $value){
...
}

When you feed a foreach with data that are not an array, you get a warning:

Warning: Invalid argument supplied for foreach() in [...]

it's not possible to refactor the get_values() function to always return an array (backward compatibility, not available source code, whatever other reason), I'm wondering which is the cleanest and most efficient way to avoid these warnings:

1. Casting $values to array
2. Initializing $values to array
3. Wrapping the foreach with an if
4. Other (please suggest)
by

3 Answers

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

foreach ((array) $items as $item) {
// ...
}
Bharatgxwzm
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, it's typed directly into SO from memory.
kshitijrana14
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.

Login / Signup to Answer the Question.