How to use count() within a loop in PHP? Put it outside

Categorized as PHP

In order to make your code cleaner, the best way is to use the count() function outside of the loop. See the example below:

// ❌ count() is called every time a loop is iterated over
for($i = 0; $i < count($arr); $i++) {
   // ..
}

// ✅ this way count() is called only once and not at every iteration
$count = count($arr);
for($i = 0; $i < $count; $i++) {
  // ..
}

What it count() in PHP?

The count() function is a built-in function in PHP that we use to count the number of elements in an array. We can also use it to count the number of characters in a string. The count() function takes an optional second parameter, which we might use to specify the mode. The default mode is 0, which counts all elements in the array, including those with a value of NULL. Mode 1 counts only elements with a value of NULL. Mode 2 counts only elements with non-NULL values. If a variable is not an array or a string, count() returns 1.

We can use the count() function within a loop to count the number of iterations. For example, the following code will count the number of times the loop iterates:

$array = array(1, 2, 3, 4, 5);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
    echo $i;
}
// outputs "01234"

When using count() within a loop, it is important to consider that the count will increment on each iteration. In the above example, if we wanted to output the array values, we would need to use $i-1 as shown below:

$array = array(1, 2, 3, 4, 5);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
    echo $array[$i-1]; 
    // outputs "12345"
}

Leave a reply

Your email address will not be published. Required fields are marked *