Invalid argument supplied for foreach() PHP error
The invalid argument supplied for foreach()
the error occurs when PHP’s built-in foreach() tries to iterate over a data structure that is not recognized as an array or
object.
Example
<?php
function get_list () {
// a list/array, a boolean FALSE is returned.
return false;
}
// Get the array
$lists = get_list();
foreach($lists as $array_item) {
//Do something.
}
Output: warning invalid argument supplied for foreach() in php
The error occurred because the get_list() function returned a boolean value instead of an array. To resolve this error, perform a check before the foreach() function so that the error can be circumvented.
The Resolve
<?php
function get_list () {
return false; //list/array, a boolean FALSE is returned.
}
$lists = get_list(); //Get the array
if (is_array($lists) || is_object($lists)) {
foreach($lists as $array_item) {
//Do something.
}
} else {
echo "Unfortunately, an error."; //If $lists was not an array
}
Output: Unfortunately, an error.