PHP loops are used to execute a statement or a statement block, multiple times until and unless a specific condition is fulfilled. This helps the programmer to save time as well as effort to write the same code several times.
Following four are the PHP loop types:
PHP
for
Loop:
The PHP
for
loop repeats a block of code until a certain condition has been met. It’s usually used for a certain number of times to execute a block of code.
Syntax:
1 2 3 4 5 | <?php for (Initialization; Condition; Increment/Decrement){ //code block } ?> |
Initialization: It is used to set the loop counter.
Condition: It decides how long the loop counter will last.
Increment/Decrement: It updates the loop counter by increment and decrement value at the end of the iteration.
Example: Let’s print numbers from 1 to 10.
1 2 3 4 5 | <?php for($i = 1; $i <= 10; $i++) { echo $i; } ?> |
In the above example, the code is initialized by 1($i = 1), the loop is running till 10 ($i <= 10) and the loop counter is updating by 1 ($i++).
Example: Let’s print a table of 2.
1 2 3 4 5 6 7 8 9 | <?php for($i = 1; $i <= 10; $i++) { echo 2 * $i."\n"; } /* If you are this code in browser then you can use <br> at the place of \n */ ?> |
You can check Print Stars Pattern In PHP article to understand the
for
loop.
PHP while loop:
PHP while loop is also a loop like for. It checks the condition ($i <= 10) at the initial.
Syntax:
1 2 3 4 5 | <?php while (condition) { //code block; } ?> |
Example:
1 2 3 4 5 6 7 | <?php $i = 1; while($i <= 10) { echo $i; $i++; } ?> |
In the above example,
$i = 1; – Initialize the counter loop ($i), and set the start value to 1.
$i <= 10 – Continue the loop, as long as $i is equal to or below 10.
$i++; – For each iteration increase the loop counter value by 1.
PHP do-while loop:
Do-while loops are very similar to while loops, except that the truth expression is checked at the end of each iteration, rather than at the start. The main difference from regular while loops is that you are guaranteed to run the first iteration of a do-while loop.
Syntax:
1 2 3 4 5 | <?php do { // Code block; } while (condition); ?> |
Example:
1 2 3 4 5 6 7 | <?php $i=1; do { echo $i; $i++; } while ($i <= 10); ?> |
In the above example,
$i = 1; – Initialize the counter loop ($i), and hold the value 1. First, execute the code inside do.
$i <= 10) – It check while condition($i <= 10).
So the given code executes 10 times.
PHP
foreach
loop:
The PHP
foreach
loop works on array or object. It provides an easy way of iterating an array of elements.
Syntax:
1 2 3 4 5 | <?php foreach ($arr as $val) { //code block } ?> |
Example:
1 2 3 4 5 6 | <?php $arr = array(1,2,3,4,5); foreach($arr as $val) { echo $val; } ?> |
1 | 12345 |
In the above example, an array defines five elements and uses
foreach
to access an array element’s value.
Please write comments if you have any queries or more information about this article.