It often happens to me to handle data that can be either an array or a null variable and to feed some foreach
with these data.
$values = get_val
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
There seems also to be a relation to the environment:
I had that "invalid argument supplied foreach()" error only in the dev environment, but not in prod (I am working on the server, not localhost).
Despite the error a var_dump indicated that the array was well there (in both cases app and dev).
The if (is_array($array))
around the foreach ($array as $subarray)
solved the problem.
Sorry, that I cannot explain the cause, but as it took me a while to figure a solution I thought of better sharing this as an observation.
$values = get_values();
foreach ((array) $values as $value){
...
}
Problem is always null and Casting is in fact the cleaning solution.
First of all, every variable must be initialized. Always.
Casting is not an option.
if get_values(); can return different type variable, this value must be checked, of course.
More concise extension of @Kris's code
function secure_iterable($var)
{
return is_iterable($var) ? $var : array();
}
foreach (secure_iterable($values) as $value)
{
//do stuff...
}
especially for using inside template code
<?php foreach (secure_iterable($values) as $value): ?>
...
<?php endforeach; ?>
Warning invalid argument supplied for foreach()
display tweets.
go to /wp-content/plugins/display-tweets-php
.
Then insert this code on line number 591, It will run perfectly.
if (is_array($tweets)) {
foreach ($tweets as $tweet)
{
...
}
}