1.2. Whence for?

So far we have learned about three different kinds of for loops, so you are probably wondering when to use each one.

A subtantial difference between the notation for($a=0 ; $a<$b ; $a++) and between for $a (0 .. ($b-1)) is that the first accommodates itself to changes in $b, while the second will iterate for a constant number of times. Of course, you can make the first one similar to the second by assigning the value of $b to a third variable that will remain constant. Still, the second notation is usually safer from that sense.

The foreach $item (@array) loop is quite handy, but sometimes when iterating over an array of items the index of the item is of importance. In that case, one may prefer to use a normal for loop.


Written by Shlomi Fish