cleanest way to skip a foreach if array is empty [duplicate]
Solution 1:
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:
foreach ((array) $items as $item) {
print $item;
}
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
, whereas is_array
wouldn't work.
Solution 2:
The best way is to initialize every bloody variable before use.
It will not only solve this silly "problem" but also save you a ton of real headaches.
So, introducing $items as $items = array();
is what you really wanted.
Solution 3:
$items = array('a','b','c');
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
Solution 4:
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 the foreach
will still error out if you use !empty
.