PHP Fix: invalid argument supplied for foreach
Here, you will get solution to fix the PHP warning "invalid argument supplied for foreach()".
The "invalid argument supplied for foreach()" error​ happens when PHP's implicit foreach() attempts to iterate over a data structure that isn't perceived as an array or object. It generally happens when deal with data that can be either an array or an invalid null variable and to start some foreach with these data. Suppose we have the following code snippet -
<?php
// create an array
$data = array();
// Define function
function getData() {
return false;
}
$data = getData();
// iterate over the data
foreach($data as $item)
{
//Do something.
}
?>
The above code returns the following warning -

As we know, the foreach() loop can only iterate over arrays or objects. The function getData() returns a boolean value instead of an array or object, that's why the warning error occurred. To fix this error, the simplest way to perform a check before the loop start, so that the warning can be handled. Here is the solution -
<?php
// create an array
$data = array();
// Define function
function getData() {
return false;
}
$data = getData();
if (is_array($data) || is_object($data))
{
// iterate over the data
foreach($data as $item)
{
// write something
}
}
else
{
echo "An error occurred.";
}
?>
Related Articles
How to display PDF file in PHP from databaseHow to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Php file based authentication
Simple PHP File Cache
How to get current directory, filename and code line number in PHP