Loops


Loops

Loops are mostly used to repeat a procedure until all of the requirements have been satisfied. The loops keep running until the requirements are satisfied. The loop will execute an unlimited number of times if the condition is not satisfied.

For the loop

<?php for ($num = 1; $num <= 5; $num += 1) { echo "$num \n"; } ?>

Output:

1 2 3 4 5

The loop is repeated five times since the criteria in the following step are not met. Thus it leaves the loop and does not restart the execution.

Looping While

It's the most basic type of looping statement. If the expression is true, the statement is executed; else, the entire code is skipped. It's mostly utilized when the value is known to be accurate.

<?php $num = 2; while ($num < 10) { $num += 2; echo $num, "\n"; } ?>

Output:

4 6 8 10

When the condition is satisfied, the statement inside the while loop is performed; otherwise, the loop is skipped.

Looping while doing something else

Even if the condition is not met, this loop is run once. It will check for conditions and run the statement until the conditions are fulfilled after the first execution.

<?php $num = 2; do { $num += 2; echo $num, "\n"; } while ($num < 10); ?>

Output:

4 6 8 10

For each assertion

It offers a technique for iterating over arrays that are formalized. An array is a collection of values with keys that point to them. The for each statement necessitates the creation of an array and the specification of the variable that will receive each element.

<?php $arr = array (15, 25, 35, 45, 55); foreach ($arr as $val) { echo "$val \n"; } $arr = array ("Ram", "Shyam"); foreach ($arr as $val) { echo "$val \n"; } ?>

Output:

15 25 35 45 55 Ram Shyam