Trusted answers to developer questions

Fixing the "invalid argument supplied for foreach()" PHP error

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

The "invalid argument supplied for foreach()" error​ occurs when PHP’s built-in foreach() tries to iterate over a data structure that is not recognized as an array or object.

Consider the code snippet below:

<?php
function getList () {
// Assume some error occurs here and instead of
// a list/array, a boolean FALSE is returned.
return false;
}
// Get the array from a function call.
$myList = getList();
//Loop through the $myList array.
foreach($myList as $arrayItem)
{
//Do something.
}
?>

The error occurred because the getList() function returned a boolean value instead of an array. The foreach() command can only iterate over arrays or objects.

To resolve this error, perform a check before the foreach() function so that the error can be circumvented. This solution is shown in the code below:

<?php
function getList () {
// Assume some error occurs here and instead of
// a list/array, a boolean FALSE is returned.
return false;
}
// Get the array from a function call.
$myList = getList();
// Check if $myList is indeed an array or an object.
if (is_array($myList) || is_object($myList))
{
// If yes, then foreach() will iterate over it.
foreach($myList as $arrayItem){
//Do something.
}
}
else // If $myList was not an array, then this block is executed.
{
echo "Unfortunately, an error occured.";
}
?>

RELATED TAGS

invalid
argument
forach
php
error
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?