Loops in PHP
Provided by Ashish Kumar / www.azooka.com
Understanding loops in PHP
When using php as your programming language, it is often required that you want your codes to be executed again and again for number of times. This is where PHP loops comes handy. PHP provides 3 different types of loops to handle your requirements.
- For Loop
- While Loop
- Foreach Loop
For loop
The for statement is used when you know how many times you want to execute a statement or a block of statements.
Syntax:
for (initialization; condition; increment) { code to be executed; }
<?php
for($i=1; $i<=100000; $i++)
{
echo "The number is " . $i . "<br>";
}
?>
While Loop
The while statement will loops through a block of code until the condition in the while statement evaluate to true. While loop is generally more suited for database work.
Syntax:
while (condition) { code to be executed; }
<?php
$x = 1;
while($x <= 100000)
{
echo "The number is: $x <br>";
$x++;
}
?>
Foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. It is generally slower than for loop.
Syntax:
foreach (array as value) { code to be executed; }
<?php
// If you had an array with fruit names and prices in you could use foreach
$fruit = array(
"orange" => "5.00",
"apple" => "2.50",
"banana" => "3.99"
);
foreach ($fruit as $key => $value) {
"$key is $value dollars <br>";
}
?>
Loops comparison
Now we see that we have multiple loops we must also know which loop is more efficient than others so that we can make faster and better applications for ourselves.
Lets check it now.
When comparing While loop vs. For loop
<?php // While Loop $a=0; while($a < 1000) { $a++; } ?> Running time: 0.116510463157895msVS.
<?php // For Loop for($a = 0; $a < 1000;) { $a++; } ?> Running time: 0.139472328421053ms
Which proves that While loop is 19.71% faster than For loop. Thus it is recommended to use while loop wherever possible.
When comparing For loop vs Foreach loop
<?php $test = array(1 => "cat", "dog" => 0, "red" => "green", 5 => 4, 3, "me"); $keys = array_keys($test); $size = sizeOf($keys); for($a = 0; $a < $size; $a++) { $t = $test[$keys[$a]]; } ?> Running time: 0.0583986610526316msVS.
<?php $test = array(1 => "cat", "dog" => 0, "red" => "green", 5 => 4, 3, "me"); foreach($test as $t){ } ?> Running time: 0.0242028168421053ms
Which proves that Foreach is 141.29% faster than For loop.
Conclusion
While the loops generally serve different purposes, we now know that the uses of individual loops and the speeds at which they perform. It is generally advised that while loops should always be used instead of for loop whenever needed for speed purposes. Similar is the situation between foreach loop and for loop. Wherever possible foreach loops should only be used. Next we will see how loops can be efficiently used with smarty templates. Stay tuned.