webketje
webketje

Reputation: 10976

(Why) should I test if an array is empty prior to a for loop?

Given an empty array $items = array();

Why should I use the following code (which I've seen used before):

if (count($items) > 0) {
   foreach ($items as $item) // do stuff here
}

instead of just

foreach ($items as $item) // do stuff here

If count($items) === 0 the loop won't execute anyway??

Upvotes: 0

Views: 117

Answers (2)

anon
anon

Reputation:

It actually depends on what you want to do. As the comments have pointed out, you may want an empty array to be a special case, so you'd like to handle that case differently. Otherwise, no warning will be thrown if you execute foreach on an empty array, you just won't get any results. A typical check you should execute is if $items is an array at all, or cast $items into an array anyway to avoid getting that warning. If you did that and $items would be generally be converted into an array of one value, i.e. the value $items had at that point.

e.g.

$items = 2;
foreach((array)$items as $item) {
    print $item; //will print 2 alright
  }

or

if(is_array($items)) {
    foreach($items as $item) {
      print $item;
    }
}
else {
    // do something here
}

Upvotes: 1

Barmar
Barmar

Reputation: 780851

You don't generally need to do the check. I see lots of code with that check, but it's often unnecessary, and I think it's usually due to ignorance on the part of the programmer. A similar pattern that I frequently see is after database queries:

if (mysqli_num_rows($stmt) > 0) {
    while ($row = mysqli_fetch_assoc($stmt)) {
        ...
    }
}

This test is also unnecessary; if no rows were found, the first fetch will return false, and the loop will stop.

The only case where it's useful is if you want to tell the user that there were no results, instead of just displaying an empty table. So you might do:

if (count($items) > 0) {
    echo "<table>";
    foreach ($items as $item) {
        // display table row
    }
    echo "</table>";
} else {
    echo "<b>No data found!</b>";
}

Upvotes: 1

Related Questions