Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to call foreach on empty php arrays in PHP 5.4?

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?

like image 971
avasin Avatar asked Dec 26 '12 21:12

avasin


1 Answers

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.

like image 182
Tom van der Woerdt Avatar answered Sep 21 '22 10:09

Tom van der Woerdt