Count in a for loop

A for loop is used to iterate over a set amount of values. This can commonly occur with arrays. We start with the first array entry and loop through each entry until there are no more entries in our array. We can do this with the following code:

$seasons = array('Summer', 'Autumn', 'Winter', 'Spring'); $totalSeasons = count($seasons); for ($i = 0; $i < $totalSeasons; $i++) { //some code that does something }

As you can see, we created a new temporary variable to store the total number of seasons which is used in our for loop. We do this as it has the advantage of calling our count function only once. Have a look at the following code.

$seasons = array('Summer', 'Autumn', 'Winter', 'Spring'); for ($i = 0; $i < count($seasons); $i++) { //some code that does something }

T-shirt with a turtle on it and the words 'Build for speed'Many programmers may look at the above code and tell you it is incorrect. They may say that you are calling the count function 4 times and it slows down your program. They may stipulate that you need to create a variable to hold the total number of items before looping through the array just like the first example. Some argue that the second example will be twice or four times as slow as the first example. All these factors maybe true and it's hard to argue against them.

The problem with what we are doing is we are concentrating on trying to speed up our program with something that won't matter. The above code runs so quickly with todays computers that you would never notice a difference. What you need to ask yourself is which one is easier to read. If you prefer the second one then do it. Don't let others tell you that it is incorrect as it is not. It is just another way to achieve your goal.

PHP is a slow scripting language compared to pure C code or machine code. Therefore trying to make speed improvements like the above is like trying to speed up a bicycle so it is faster than a race car.