The forEach() loop was introduced in ES6 (ECMAScript 2015) and it executes the given function once for each element in an array in ascending order. It doesn't execute the callback function for empty array elements.
From the PHP manual: break ends execution of the current for, foreach, while, do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. foreach ( $array as $value ) { if ( $value == 3 ) continue; # Skips # Code goes here... }
break ends execution of the current for , foreach , while , do-while or switch structure.
There is no major "performance" difference, because the differences are located inside the logic. You use foreach for array iteration, without integers as keys. You use for for array iteration with integers as keys. etc.
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.
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.
$items = array('a','b','c');
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With