As i remember, before i always had to check count($array) before making a foreach. From that times i always make this doublecheck, and wanted to know, does it make sense nowdays with php 5.4?
I've set error_reporting to E_ALL and executed following script:
$x = [];
foreach($x as $y) {
var_dump($y);
}
and got no notice (as i remember, previously, perhaps it was php5.3) i was getting notice.
Is it safe now using foreach on array, that is empty?
As long as it's an array, there's no need to check the amount of items in it. Just make sure to pass it an actual iterable object: for example, don't pass it random objects or NULL
.
But yes, foreach([] as $nothing) {}
is safe.
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