0

I have done some research but I haven't found a straight answer to my question.

Is doing a count before a loop is the good way to do it ?

Is that better to do :

if(count(array) > 0){
    foreach(array as entry){

    }
}

OR

foreach(array as entry){

}

From my point of view, the count is an extra step because if the array is empty, we won't loop.

What do you think about it ?

Salman A
  • 262,204
  • 82
  • 430
  • 521
David Bélanger
  • 7,400
  • 4
  • 37
  • 55
  • 1
    I don't use the extract check in any language that supports "enumerating empty sequences". If array does not represent something that can be enumerated then yes - a check *is* required. I write code to avoid this case, where practical. –  Mar 26 '13 at 18:03
  • I would include either the count or if(!empty(array)), but its not required, I would only require it if you had some other kind of iterable object – SoluableNonagon Mar 26 '13 at 18:03
  • 1
    You might want to read http://stackoverflow.com/questions/10057671/how-foreach-actually-works – Anirudh Ramanathan Mar 26 '13 at 18:06

3 Answers3

4

if there is nothing in the array, the foreach loop will loop 0 times. Checking the count ahead would be un-necessary. Depending on what the possible values for $array are, you would probably be better to test for is_array() because a foreach will throw an error if $array is not an array.

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
1

Lets try some simple test;

Test 1

$array = "string";
foreach ( $array as $entry ) {
}

Output

Warning: Invalid argument supplied for foreach()

Test 2

$array = "string";
if (count($array) > 0) {
    foreach ( $array as $entry ) {
    }
}

Output

Warning: Invalid argument supplied for foreach()

Test 3

$array = "string";
if (is_array($array) || $array instanceof Traversable) {
    foreach ( $array as $entry ) {
    }
}

Output

 No error

You don't have to validate all the time .. but when you are not sure of the value ... you should check if its valid before you loop.

Baba
  • 94,024
  • 28
  • 166
  • 217
  • I prefer the way you do it with the test number 3. We first look if it's an array and/or a Traversable variable/object call it whatever you want. Thanks you. – David Bélanger Mar 28 '13 at 12:59
0

If you go with count() it's similar to doing is_array(). Foreach will give you a error if it is not an array.

A better way, imo, is going with if(!empty($array)){

Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51