PHP Fix: invalid argument supplied for foreach
Here, you will get a 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 dealing 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 is to perform a check before the loop starts 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
File Upload Validation in PHPPHP exception examples
PHP error_reporting() function
PHP File Upload MIME Type Validation
PHP Logging Errors Into a File
PHP 7 Error Handling
PHP Programming Error Types
Php file based authentication
Simple PHP File Cache
PHP Static Methods & Properties
How to pass array in URL query string using PHP
PHP remove last character from string
Remove duplicates from array PHP
PHP capitalize first letter
PHP calculate percentage of total
PHP String Contains
Fibonacci number program
PHP reverse a string without predefined function
PHP random quote generator
PHP substr() function