Different PHP Loops

Hey Folks,

Now its time to get aware with different php loops in php. Followin is the information about do..while loop, while loop, for loop and foreach.

Basic Loop Concept

You may think how loop is useful and why it is needed ? Here is simple way of explanation. If you want to add 10 numbers, you can do it using arithmetic operator and variables.

<?php
$total = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
?>

Now if you want to add 100 numbers, 1000 numbers and even more. Will you write such a long code? Answer is no. Because its a waste of time. So loop comes in picture. You can do such tasks using loop.

For Loop

Have a look at example for adding 1 to 1000 numbers using FOR loop.

<?php
$total = 0; 
for($i=1;$i<=1000;$i++) {
$total += $i; 
}
echo $total;
?>

Now you can see total of 1 to 1000 numbers on your screen. Pretty simple!
Syntax of FOR Loop.

<?php

$i=1;
$i<=1000;
$i++;

?>

While Loop

Have a look at same example for adding 1 to 1000 numbers but instead of for loop, we will use while loop.

<?php
$total = 0; // Define Total Variable to 0
$i = 1;
while($i<=1000) {
 $total += $i; // Adding value of $i into $total variable
 $i++;
}
echo $total;
?>

Now you can see total of 1 to 1000 numbers on your screen. Pretty simple!
Syntax of WHILE Loop.
<?php

$i=1;
$i<=1000;
$i++;

?>

Do While Loop

Do while loop is identical to while loop but only difference is that condition checks comes at end in do while loop. so your statements will execute at least once before it checks condition.

<?php
$total = 0; // Define Total Variable to 0
$i = 1;
do {
 $total += $i; // Adding value of $i into $total variable
 $i++;
} while($i<=1000);

echo $total;
?>

Now you can see total of 1 to 1000 numbers on your screen. Pretty simple!
Syntax of DO WHILE Loop.

<?php

$i=1 ; 
$i<=1000;
$i++;   

?>
Foreach Loop

Foreach loop is different than above loops. You can use foreach loop for parsing array. I will explain about Array in my next post but have a look at the example.
<?php
$total = 0; // Define Total Variable to 0
$num_arr = array(1, 2, 3, 4, 5);
foreach ($num_arr as $single_val) {
    $total += $single_val;
}
?>

Now you can see total of all array numbers on your screen. Pretty simple!
Syntax of FOREACH Loop. You can also parse array as Key Value pair. Instead of $single_val, you need to write $k=>$single_val. You will get Key value in $k variable.

<?php

$num_arr;

?>

Isn’t it easy to work with Different PHP Loops in PHP ?