link-to-php-article

Improve your for()-loops. A common mistake explained.

For()-loops can be very handy, but they are often used the wrong way.

There are always more ways to do something, but let’s say you want to add a number to the values of an array using a for()-loop.

This is what you often see:

1
2
3
$arr = ('item', 'other_item', 'word', 'phrase');
for ( $i = 0; $i < count($arr); $i++ )
    $arr[ $i ] = $arr[ $i ] . '-' . $i;

What does this code do?
On line 1, the array is created and filled with some values.
On line 2, the for()-loop starts. The loop is defined as “start with $i = 0; run until $i is equal or higher than the count of the array elements; increase $i with 1 on every new run”
On line 3, the value of $arr element with index $i, is set to it’s initial value with ‘-‘ and the value of $i added at the end.
(We left out the {} because there is only one commandline in the for()-loop.)

This code will run just fine. The problem here is the recalculation of the length of $arr for every run.
The array does not changed, the value will be the same for every run. It is better to put this number in a variable and use that.

Better version

1
2
3
4
$arr = ('item', 'other_item', 'word', 'phrase');
$arr_length = count($arr);
for ( $i = 0; $i < $arr_length; $i++ )
    $arr[ $i ] = $arr[ $i ] . '-' . $i;

Now the calculation is only done once.
When working with small arrays there will not be much of a difference, but imagine going over thousands of products.

never-changes-a-winning-team
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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