DEV Community

Discussion on: The PHP for loop

Collapse
chuniversiteit profile image
Chun Fei Lung

Neat explanations!

Depending on the size of your list, count() can indeed be very expensive if you do it repeatedly. There’s no need to define it outside of your for though:

for ($i = 0, $treesCount = count($trees); $i < $treesCount; $i++) {
    echo $trees[$i] . ' ';
}
Enter fullscreen mode Exit fullscreen mode

And while descriptive variable names are usually a good thing, $i is kind of an exception to that rule. Its usage has become so idiomatic across languages that anyone who sees for ($i = 0; $i < $someNumber; ++$i) instantly understands what its purpose is, especially since it is virtually always used to access an array index (as in the example above).