PHP: Fix for “Invalid argument supplied for foreach()”

At some point or another, every PHP developer has come across the following error:

“Warning: Invalid argument supplied for foreach() on line [INSERT LINE NUMBER HERE]”

The error is caused when the variable that foreach is attempting to iterate over is not an array.

For example, let us say that I have a function called get_user_posts. This function is supposed to return an array of user comments. However, if no comments exist, then the function returns a boolean FALSE value.

<?php

//Get user's posts.
$posts = get_user_posts($userId);

//Loop through the $posts array.
foreach($posts as $userPost){
    //Do something.
}

In the code snippet above, I’ve made the assumption that the $posts variable will always be an array. However, if the get_user_posts function returns a boolean FALSE value, then my foreach loop won’t work and PHP will dump out the following error message:

Warning: Invalid argument supplied for foreach() on line 7

Hmm. Not good.

“So, how do we fix this?”

The fix depends on what the code is supposed to be doing. i.e. If the get_user_posts function is supposed to return an array at all times, then obviously, you will need to investigate why it is returning a boolean FALSE value or a NULL value. The cause could be a number of things:

  1. A failure to declare a “default” empty array.
  2. A failed database query.
  3. The array being overwritten or unset (common in array-heavy scripts, where memory limits are being hit and the developer is forced to unset arrays that he or she is “finished” with).

In the past, I’ve come across APIs and functions that return a FALSE value when no results are present. If this is the case, then you could add the following check to your code:

<?php

//Get user's posts.
$posts = get_user_posts($userId);

//Loop through the $posts array IF it is an array.
if(is_array($posts)){
    foreach($posts as $userPost){
        //Do something.
    }
}

Above, we are using the is_array function to check if $posts is an array, BEFORE we attempt to loop through it using the foreach construct.

As I said – it all depends on what the script is supposed to be doing. Adding the is_array check when the variable in question should be an array is not wise, as you will be covering up a bug that shouldn’t exist in the first place.

Facebook Comments