php error invalid argument supplied for foreach()

PHP is a very famous coding languge for making front-end as well as back-end customized websites in technology world. In fact, not like other languages, php is relatively easy to learn by your own efforts.

However, Every time when PHP developers try to invent something functionally, they face some of very basic issues and php error such as cannot modify header or move_uploaded_file() error.

In this article, we’re going to see a very simple yet frustrating problem that is: Invalid argument for foreach(). So Let’s see why you’re getting this error and what to do to solve it:

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, even with basic empty array() phrase, then you will face this error.

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 (“true”, “10” or “abc”).

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 PHP Error?

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.
    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!