for($x = 0; $x <= 100; $x++){
}
?></eeSnippet>
Easy and simple to understand.
The code we will be using to benchmark this loop is as follows:<eeSnippet><?php
$start = microtime(true);
for($x = 0; $x <= 5000000; $x++){
}
$end = microtime(true);
$time = $end - $start;
echo "FOR loop:<br/>" . $time . " seconds";
?></eeSnippet></step><step
$x = 0;
while($x <= 100){
$x++;
}
?></eeSnippet>
Ever so slightly more complex but it's essentially the same items organised a different way.
The code we will be using to benchmark this loop is as follows:<eeSnippet><?php
$start = microtime(true);
$x = 0;
while($x <= 5000000){
$x++;
}
$end = microtime(true);
$time = $end - $start;
echo "WHILE loop:<br/>" . $time . " seconds";
?></eeSnippet></step><step
<eeSnippet><?php
// Start FOR test
$start = microtime(true);
for($x = 0; $x <= 5000000; $x++){
}
$end = microtime(true);
$time = $end - $start;
echo "FOR loop:<br/>" . $time . " seconds";
// End FOR test
echo "<br/>";
// Start WHILE test
$start = microtime(true);
$x = 0;
while($x <= 5000000){
$x++;
}
$end = microtime(true);
$time = $end - $start;
echo "WHILE loop:<br/>" . $time . " seconds";
// End WHILE test
?></eeSnippet>Upon executing this script, the results were as follows:
<eeQuote>FOR loop:
0.69475388526917 seconds
WHILE loop:
0.60405921936035 seconds</eeQuote>
You will notice that, in this test, WHILE appears to be the more efficient loop. There are arguments for and against this (see the links in the references below).
The results do vary, however, WHILE always seems to come out faster. See what you think!</step><step="5" title="References">http://
http://mgccl.com/2007/03/2
http://cosminb.blogspot.co