Mastering For Loops in PHP: A Comprehensive Guide:

For loop:

example:

<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}
?>

1 2 3 4 5

While Loop:

<?php
$num = 1;
while ($num <= 5) {
    echo $num . " ";
    $num++;
}
?>

1 2 3 4 5

Do-While Loop:

<?php
$num = 1;
do {
    echo $num . " ";
    $num++;
} while ($num <= 5);
?>

1 2 3 4 5

Foreach Loop:

<?php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
    echo $color . " ";
}
?>

Red Green Blue

Nested Loop (For inside For):

<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        echo $i * $j . " ";
    }
    echo "<br>";
}
?>

1 2 3
2 4 6
3 6 9

Leave a Reply

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