Loop in PHP

Loop is used to execute a prticular action untill the condition is true.Basically loop is used to automate repetitive a action to save time we use four loop in php
for   : for loops execute a block of code a specified number of times.

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

Example
<?php
for ($x = 0; $x <= 15; $x++) {
echo “The output is: $x <br>”;
}
?>
while : while loops execute a block of code until a specified condition is true.

Syntax
while (condition is true) {
code to be executed;
}
Example
<?php
$x = 0;

while($x <= 15) {
echo “Output is: $x <br>”;
$x++;
}
?>

do-while  : do-while loops execute a block of code once, and then repeats the loop untill a condition is true.

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

Example
<?php
$x = 0;

do {
echo "The Output is: $x <br>";
$x++;
} while ($x <= 15);
?>

foreach   : foreach loops execute a block of code for each element in an array.

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

Example
<?php
$colors = array("Maruti", "Toyoto", "Tata");

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

foreach   : foreach loops execute a block of code for each element in an array.

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

Example
<?php
$colors = array("Maruti", "Toyoto", "Tata");

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

Leave a Reply

Your email address will not be published. Required fields are marked *