This question already has an answer here:
- Invalid argument supplied for foreach() 18 answers
Not a major problem but I was wondering if there is a cleaner way to do this. It would be good to avoid nesting my code with an unnecessary if statement. If $items
is empty php throws an error.
$items = array('a','b','c');
if(!empty($items)) { // <-Remove this if statement
foreach($items as $item) {
print $item;
}
}
I could probably just use the '@' error suppressor, but that would be a bit hacky.
There are a million ways to do this.
The first one would be to go ahead and run the array through foreach anyway, assuming you do have an array.
In other cases this is what you might need:
Note: to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty (emphasis is mine). A value of true, false, numbers or strings is not considered empty. In addition, this would work with objects implementing
\Traversable
, whereasis_array
wouldn't work.Ternary logic gets it down to one line with no errors. This solves the issue of improperly cast variables and undefined variables.
It is a bit of a pain to write, but is the safest way to handle it.
I wouldn't recommend suppressing the warning output. I would, however, recommend using
is_array
instead of!empty
. If$items
happens to be a nonzero scalar, then theforeach
will still error out if you use!empty
.i've got the following function in my "standard library"
Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions
Best practice is to define variable as an array at the very top of your code.
foreach((array)$myArr as $oneItem) { .. }
will also work but you will duplicate this (array) conversion everytime you need to loop through the array.
since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.