Verification: a143cc29221c9be0

Php array with for loop


The "wrong" way

The following example loops through an array in the variable $array:

for($i = 0; $i 

The count() function is called on each loop which adds extra unecessary overhead. Even if the array only has a couple of items in it processing will still take longer than assigning count() to a variable.

The "right" way

Here’s one way of doing it the "right" way:

$j = count($array);
for($i = 0; $i 

The count is now assigned to the variable $j so the function is only called once.

Another way of doing the above is like so:

for($i = 0, $j = count($array); $i 

The assignment $j = count($array) is part of the for loop, separated by a comma from the $i = 0 assignment. It is only called once at the start of the loop. It is not necesssarily superior to the first "right" example above but it does reduce the number of lines of code by one and means the purpose of the variable is clearly for of the loop.