Readable and faster “for” loops in PHP

After some discussions on Twitter, I would like to show you some ways to write for loops in PHP, but more readable and fast.

Classic for loop

The most common, and probably used, way to write a for loop, is by using the for keyword like this :

foreach with range()

But you could write the same loop with a foreach, and using the range PHP function :

This way is more readable, but sadly, it’s a lot much slower : 2 to 5 times slower than the for loop.

while loop and decrementation

Another readable way to make something similar to a for loop, is by decrementing in a while like this :

No, the arrow (–>) is not a new operator, it’s just the decrement operator — with the comparison operator >. You could also write it like this :

What about the speed ? Well, it’s 2 times faster than the for loop ;). This way, you have a great readability and speed on your loop.

Check it online or try it yourself :