Invalid argument supplied for foreach

Empty array
Invalid argument supplied for foreach can happen if you try to do a foreach on an variable that isn't an array. Maybe it is "supposed to" be an array, maybe you thought it was an array, but sorry -- it isn't.

For example foreach(null as $element) is going to fail bigtime.

Lots of time what will happen is that a method will expect an array but not get it, e.g. function foo($anArray) {   foreach($anArray as $element) {     echo $element; } }

In such cases, PHP will helpfully tell you that $anArray is an invalid argument, but that doesn't tell you who passed the bogus $anArray to foo. If you are the owner of foo, you might want to put in a check and return a code that indicates whether or not foo succeeded or failed:

function foo($anArray) {   if(empty($anArray)) {     return false; }   foreach($anArray as $element) {     echo $element; }   return true; }

Then, if you get a false back from foo, you can force an error in the calling routine. It is much easier to debug in the calling routine than in the receiving routine.

If foo is supposed to return a value -- say a number -- then you could return a NULL if it messed up.