Common programming mistake using for()-loop

in php •  7 years ago 

Most programming languages have an implementation for the for()-loop.

In subcode it looks like:

for ( counter; condition; counterchange) {
   // do something
}

An actual code snippet in PHP would look like this:

for ( $i = 0; $i < $some_variable; $i++ ) {
       // do something
}

This code will start with $i having a value of zero, the value of $i will be checked against the value of $some_value. This check is performed for every loop. As long as $i is smaller than $some_value this loop will perform //do something, increase $i with 1 (that is what $i++ does) and start over. Once $i is equal to or larger than $some_value the for()-loop will stop.

The mistake many people make is with the $some_variable value. This is often the length of an array or string. People use the length like this:


$my_array = array('appel', 'kiwi', 'tomato', 'grape', 'melon');

for ( $i = 0; $i < count($my_array); $i++ ) {
    // do something
}

This code will work, but it does mean the length of the array ( count($my_array) ) is being calculated for every new loop. This is not necessary, as in many cases the array doesn't change.

It is better to use it like this:


$my_array = array('appel', 'kiwi', 'tomato', 'grape', 'melon');
$len      = count($my_array);

for ( $i = 0; $i < $len; $i++ ) {
    // do something
}

Now the length of the array is only calculated once and used multiple times.PHP-logo.png

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!