PHP Warning: Invalid argument supplied for foreach()
Solution:
You should check that what you are passing to foreach
is an array by using the is_array function
If you are not sure it's going to be an array you can always check using the following PHP example code:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
Answer
Solution:
This means that you are doing a foreach on something that is not an array.
Check out all your foreach statements, and look if the thing before the as
, to make sure it is actually an array. Use var_dump
to dump it.
Then fix the one where it isn't an array.
How to reproduce this error:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //the warning happens on this line.
print "ok";
}
?>
Make sure $skipper
is an array.
Answer
Solution:
Because, on whatever line the error is occurring at (you didn't tell us which that is), you're passing something to foreach
that is not an array.
Look at what you're passing into foreach
, determine what it is (with ), find out why it's not an array... and fix it.
Basic, basic debugging.
Answer
Solution:
Try this.
if(is_array($value) || is_object($value)){
foreach($value as $item){
//somecode
}
}
Source