How to Fix the "Invalid Argument Supplied for Foreach()" PHP Error

The "invalid argument supplied for foreach()" error can trigger once the built-in foreach of PHP attempts to iterate over a data structure, which is not recognized as an array or an object.

Let’s check out a code snippet:

<?php
function getList()
{
    // Several errors occurs here and instead of
    // an array/list, a boolean FALSE is returned.
    return false;
}

// Retrieve the array from a function call.
$myList = getList();

//Loop through the $myList array.
foreach ($myList as $arrayItem) {
    //Do something.
}
?>

The output of this code will lead to the "invalid argument supplied for foreach()" error.

Let’s figure out why it happens and how to resolve the error.

The main cause of the error is that instead of an array a boolean value is returned by the getlist() function.

It is essential to note that the foreach() command is capable of iterating merely over objects or arrays.

The resolution to this error can be quite simple. All you need is checking before the foreach command for being circumvented.

The code below clearly shows how to resolve the error:

<?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 occurred.";
}
?>

Describing foreach() in PHP

In PHP, the foreach() construct allows iterating over arrays straightforwardly.

It only operates on objects and array. After using it on a variable with a different data type, it leads to an error.

In PHP 5, once foreach begins to execute first, the internal array pointer is reset to the array’s first element automatically. Hence, there is no necessity in calling the reset() function before the foreach loop.

To get more information about foreach() in PHP, you can refer to this source.

Do you find this helpful?

Related articles