php error invalid argument supplied for foreach()

Every PHP developer face this issue at some point in while working with php:

Warning: Invalid argument supplied for foreach() in C:\wamp64\www\errortesting\invalid-foreach-argument.php on line 3

The error will occur when the variable you have passed to foreach loop to iterate, is not an array or is not defined.

For example, If I am iterating through $test variable and that variable is not defined, then you will face this error.

Let’s look into the example itself to clear the concept. Here I am using a function named get_users() to get the array of users.



//get user’s array
$names = get_users();


//loop through users array
foreach($names as $n){
// Do your stuff
}

Now, in this code I am iterating $names array through foreach() and that must be in array format. If the function get_users() will return response in any format other than array, it will throw an error. Suppose function is returning a Boolean or integer or varchar value.

Due to improper return value, foreach loop will not execute and throw you an error of invalid argument. It means you have not applied proper variable format.

And it’s not good, right?

Now, question is how to fix this?

To fix this issue, you need to recheck your code. If you are getting this from any function, like I used here get_users(), Then check whether that function is returning an array format response or not.

If you are using variable having array values then check the format of array. Below can be the cases to get an error:

  • May be you forgot to declare an empty array. (For example, $test = array())
  • Your database query is not proper.
  • According to your script, a global declaration may be necessary.
  • In heavy script, you may have overwritten or unset the array.


Let’s see how you can stop an error generation:

  1. You can use is_array() function to check if the returned value is array or not.

    //loop through result if it is array.
    if(is_array($names)){
    Foreach($names as $name){
    // do your stuff
    }
    }

  2. If you are having results from database query then you can check for count of result. Use mysqli_num_rows() function to check if result having more than 0 rows.

Error generation depends on your writing ability of clean and error free code. Error solution is not only enough, you should try error prevention too.

Hope this helps you. Best of luck for you code!