cleanest way to skip a foreach if array is empty
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.
If variable you need could be boolean false
- eg. when no records are returned from database or array
- when records are returned, you can do following:
foreach (($result ? $result : array()) as $item)
echo $item;
Approach with cast((Array)$result
) produces an array of count 1 when variable is boolean false
which isn't what you probably want.
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.
$items = array('a','b','c');
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}