"For" more clearly expresses your intentions
Functionally, your two examples are the same. But they express different intentions.
while means "I don't know how long this condition will last, but as long as it does, do it."for means "I have a certain number of repetitions to execute."
You can use it when you mean another, but it is more difficult to read the code.
Other reasons are preferred here for why for here
- It is more concise and puts all the loop information in one place.
- It makes
$i local variable for the loop
Don't forget foreach
Personally, the loop that I use most often in PHP is foreach . If you find yourself doing things like this:
for ($i=0; $i < count($some_array); $i++){ echo $some_array[$i]; }
... then try the following:
foreach ($some_array as $item){ echo $item; }
Faster to enter, easier to read.
Nathan long
source share