Wednesday 8 August 2018

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

0 comments:

Post a Comment