PHP Loops


Loops are used to Exicute the Same block of code as a specified number of time.

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

For Loop

PHP for loops execute a block of code a specified number of times.

The for loop is used when you know in advance how many times the script should run.

Syntax

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

Parameters

  • 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

The example below displays the numbers from 1 to 5:

Example

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

Run Example>>

Nested For Loop

Example

<?php
for ($x = 1; $x <= 5; $x++) {
    echo "The Value of X is: $x <br>";
for ($y = 1; $y <= $x; $y++) {
    echo "The Value of Y is: $y <br>";
}
}
?>

Run Example>>

Note:To display pattern ,nested for loop is used.

Print The Triangle

*
* *
* * *
* * * *
* * * * *

Example

for ($i=1;$i<=5;$i++)
{
for($j=1;$j<=$i;$j++)
{
echo "* ";
}
echo"<br>";
}

Run Example>>