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

1

7

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?

Complement answered 26/12, 2012 at 21:25 Comment(5)
It was always safe to enumerate an empty array. What notice did you receive before? Perhaps it was due to some other issue?Highpriced
nope, i'm sure, i remember i was getting some notice about empty array O_o, don't remember it's text :(Complement
Iterating an empty array has always been safe. If the array doesn't exist or is null though, that's another story.Battiste
Ok.. now i'll be very sure, thanks!Complement
Was it Invalid argument supplied for foreach()? Wouldn't show on an array but would if you have defined the var but not as an array.Ji
D
16

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.

Dieselelectric answered 26/12, 2012 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.