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?

Paolo Stefan
  • 10,112
  • 5
  • 45
  • 64
avasin
  • 9,186
  • 18
  • 80
  • 127
  • 4
    It was always safe to enumerate an empty array. What notice did you receive before? Perhaps it was due to some other issue? – cdhowie Dec 26 '12 at 21:26
  • nope, i'm sure, i remember i was getting some notice about empty array O_o, don't remember it's text :( – avasin Dec 26 '12 at 21:27
  • 7
    Iterating an empty array has always been safe. If the array doesn't exist or is `null` though, that's another story. – Eric Petroelje Dec 26 '12 at 21:28
  • Ok.. now i'll be very sure, thanks! – avasin Dec 26 '12 at 21:29
  • 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. – Popnoodles Dec 26 '12 at 21:29

1 Answers1

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.

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105