Using count() in for()-loops
Since I just stumbled across it again, here's a common "mistake" often done, which can be avoided very easily. Situation is an array, that is looped over using for(). It might look something like this:
$elements = array(
'Element 1',
'Element 2',
'Element 3',
'Element 4',
'Element 5',
);
for ($i = 1; $i <= count($elements); $i++) {
print('Processing Element #' .$i . PHP_EOL);
}
This is bad coding style because the count() is in the loop header. In this case everytime the loop moves on to the next element, the function count() is called (here 5 times), although the size of the array never changes. The right (and more performant) way to do this, would be:
$elementsCount = count($elements);
for ($i = 1; $i <= $elementsCount; $i++) {
print('Processing Element #' .$i . PHP_EOL);
}
Now count() is only called once and the code does exactly the same.
3 comments
Loïc Hoguin
17.01.2009, 12:55 o'clock
He's right, it's the expr2 that is evaluated with each loop. The example is wrong and off-topic but fix it with a good example and the advice may become viable.
Dominik Jungowski
17.01.2009, 13:10 o'clock
Whoops, you are totally right. Thanks for the feedback, i just fixed the example
16. Januar 2009
comments feed
recent posts
david
17.01.2009, 03:01 o'clock
What you are writing is plain wrong. This is from the php.net for loop documentation :
for (expr1; expr2; expr3)
The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.