php loops

Often in PHP you need the same block of code to run repeatedly in a row. We can use loops to perform such tasks instead of writing similar codes again and again. In PHP, we have the following looping statements.

while - loops through a block of code as long as the specified condition is true

do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true

for - loops through a block of code a specified number of times

foreach - loops through a block of code for each element in an array

WHILE LOOP

Syntax

initial point;
while (condition is true) {
	code to be executed;
}  

Example

$x = 1; 
while($x <= 5) {
	echo "The number is: $x <br>";
	$x++;
}   

DO WHILE LOOP

Syntax

initial point;
do {
	code to be executed;
} while (condition is true);

Example

$x = 1; 
do {
	echo "The number is: $x <br>";
	$x++;
} while ($x <= 5);

FOR LOOP

Syntax

for (init counter; test counter; increment counter) {
	code to be executed;
}  

init counter: Initialize the loop counter value

test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

increment counter: Increases the loop counter value

Example

$x = 0;
for ($x = 0; $x <= 10; $x++) {
	echo "The number is: $x <br>";
}   

FOREACH LOOP

Syntax

foreach ($array as $value) {
	code to be executed;
}  

Example

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $value) {
echo "$value <br>";
}  

Shorthand for foreach loop

<?php foreach($a as $d): ?> <?php endforeach: ?>

BREAK AND CONTINUE

Break stops further execution of the code while continue returns the execution to the top level of the code again and makes it re-run from there. but it might create an infinite loop as the value will be the same while going to the conditional statement so we need to increase the value before the continue command to make the code run properly.

Example

$i = 1;
while ($i <= 10){
	if($i == 5){
	break;
}
	echo 'Hello World' . ' 
'; $i++; }
$i = 1;
while ($i <= 10){
	if($i == 5){
	echo 'FIVE';
	$i++;
	continue;
}
	echo 'Hello World' . ' 
'; $i++; }

0 Like 0 Dislike 0 Comment Share

Leave a comment