Equivalence of for Loop and while Loop
Learn how to convert a for loop into a while loop in this lesson.
We'll cover the following
Let’s look at an example of for
loop:
for ($i=0 ; $i<10 ; $i++){$i = $i*2;print "Value of i is: $i\n";}print "Final value of i is: $i\n";
Converting a for
loop into a while
loop
The above for
loop can easily be rewritten as a while
loop.
$i=0 ;while ($i<10) {$i = $i*2;print "Value of i is: $i\n";$i++;}print "Final value of i is: $i\n";
for
loop vs. while
loop
A for
loop is more often used by programmers due to its conciseness as well as its separation of the looping logic.
A while
loop is often preferred if a certain section of code needs to be repeated for an indefinite number of times until a condition is met.
However, the two are equivalent. Therefore, it is ultimately a coding style decision, not a technical decision about whether to use one or the other.