Improve PHP 'for' loop [duplicate] Improve PHP 'for' loop [duplicate] php php

Improve PHP 'for' loop [duplicate]


for($i = 0; $i <= count($data); $i++){}

In this example for every iteration it has to count($data) again.

for($i = 0, $iMax = count($data); $i <= $iMax; $i++){}

In this example it only needs to count($data) once.

That's the difference.


If you execute the count() inside your for loop, then it's executed every iteration, and calling the function is a performance overhead.

If instead you call count() before the for loop and assign the result to a variable, then compare against the variable in the for loop, you don't haver the function call overhead, so it's faster


By having the loop in the manner you do, each iteration it needs to evaluate count($data). If you've got a lot of items in the list, it could take a while (relatively) to count those items, and it has to do it each time.

The hint it is diving you is to set a variable to the value of count($data) at the beginning and then use that variable as the loop limit, when it's only evaluated once.

This can be done in two ways:

$loopMax = count($data);for ($i = 0; $i <= $loopMax; $i++) {    // Your code here}

Or

for ($i=0, $loopMax = count($data); $i <= $loopMax; $i++) {    // your code here}