Are you wondering why I am writing this very basic article of type of PHP loops? Just because sometime we get confused which loop we need to use in program based on the situation.
There are 4 type of loop in PHP
- For Loop – When we know the number of iterations
- While Loop – When we don’t know number of iterations
- Do..While Loop – When we don’t know number of iterations and we want to perform some actions for each loop process. For example. Generating a random number each time till we got 6. This is the case in dice rolling example.
- Foreach Loop – This is loop for arrays.
If the condition in a while loop is false, then not a single statement inside the Loop will be executed, whereas in a do-while Loop, if the condition is false, then the body of the Loop is executed at least once.
Here is the simple example to demonstrate loops.
<?php
echo 'Hello world';
// There are 4 types of loop
// for
// while
// do..while
// foreach
echo '<br>';
// For loop is used when the number of iterations is already known.
for ($i = 1; $i < 20; $i++) {
# code...
echo $i . '</br>';
}
echo '</br>';
// While loop is used when the number of iterations is already Unknown
$a = 1;
while ($a <= 5) {
# code...
echo $a . '</br>';
$a++;
}
echo '</br>';
// perform this action in loop untill condition fulfilled.
do {
# code...
$b = rand(1, 6);
echo $b . '</br>';
} while ($b != 6);
// loops through a block of code for each element in an array
echo '<br>';
$ary = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
foreach ($ary as $key => $value) {
# code...
echo $key . ' - ' . $value;
echo '<br>';
}