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
Exceptional case for this notice occurs if you set array to null inside foreach loop
if (is_array($values))
{
foreach ($values as $value)
{
$values = null;//WARNING!!!
}
}
How about this solution:
$type = gettype($your_iteratable);
$types = array(
'array',
'object'
);
if (in_array($type, $types)) {
// foreach code comes here
}
foreach ($arr ?: [] as $elem) {
// Do something
}
This doesen't check if it is an array, but skips the loop if the variable is null or an empty array.
What about defining an empty array as fallback if get_value()
is empty?
I can't think of a shortest way.
$values = get_values() ?: [];
foreach ($values as $value){
...
}
How about this one? lot cleaner and all in single line.
foreach ((array) $items as $item) {
// ...
}
Please do not depend on casting as a solution, even though others are suggesting this as a valid option to prevent an error, it might cause another one.
Be aware: If you expect a specific form of array to be returned, this might fail you. More checks are required for that.
E.g. casting a boolean to an array
(array)bool
, will NOT result in an empty array, but an array with one element containing the boolean value as an int:[0=>0]
or[0=>1]
.
I wrote a quick test to present this problem. (Here is a backup Test in case the first test url fails.)
Included are tests for: null
, false
, true
, a class
, an array
and undefined
.
Always test your input before using it in foreach. Suggestions:
$array = is_array($var) or is_object($var) ? $var : [] ;
try{}catch(){}
blocksarray_key_exists
on a specific key, or test the depth of an array (when it is one !).