Fix Invalid argument supplied for foreach() PHP Warning

Introduction

PHP is the most popular scripting programming language used for web development. WordPress world no 1 CMS also developed on PHP and more than 75% of web powered by PHP.

While working on PHP code, most of us have faced fix invalid argument supplied for foreach() warning many times.

Today, we are going to discuss why this warning comes and how we can fix this.

Problem

This error normally appears when the variable that should be an array in the foreach loop doesn’t contain an array.

Or in other words, when foreach() function tries to iterate over a variable is not recognized as an array.

$variable = getVariable();  // function return some value, might be boolean, list or array

foreach($variable as $k => $v){  
  // execute code
}

In the above code example, we can see $variable is being used in foreach() loop and there are 90% chances that it will throw the PHP warning. Because we don’t know that what getVariable() function is actually returning.

Solutions

So solution for Fix Invalid argument supplied for foreach(), when we are going to use any variable with foreach() that is actually an array, always define it properly before original function call and foreach() loop.

$example = array();

Then it will treat $example an empty array so that if nothing is loaded into it, foreach loop will actually see an array, even if that array is empty.

Also, always use is_array() to check if given variable is array or not before foreach() loop

Solution for Fix invalid argument supplied for foreach() with Example

$variable = array();  // define an array
function getVariable(
// some code + query
 return $variable;
)
$variable = getVariable();  // function will return value as an array now
// check if $variable is array  or not
if(is_array($variable) && isset($variable)) {

  foreach($variable as $k => $v){  
   // execute code
  }
} else {
   echo "print error message";
}

Hope I am able to solve this issue. Please write in the comment box if you have something to discuss this. Sharing is caring.

Leave a Reply