PHP While Loop Example

 Here is a simple example of a PHP while loop:

<?php

$x = 1;

while ($x <= 5) {

  echo "The number is: $x <br>";

  $x++;

}

?>


This code will print the numbers from 1 to 5, one per line.


The while loop works by first initializing a variable, in this case $x, to a value. In this case, $x is initialized to 1. Then, the loop checks to see if the value of $x is less than or equal to 5. If it is, the loop body is executed. The loop body in this case is simply a call to the echo function, which prints the value of $x followed by a newline character. After the loop body is executed, the value of $x is incremented by 1. This process repeats until the value of $x is no longer less than or equal to 5. When this happens, the loop terminates.


Here is another example of a PHP while loop:


<?php

$i = 1;

$j = 1;

while ($i <= 5) {

  while ($j <= $i) {

    echo "*";

    $j++;

  }

  echo "<br>";

  $i++;

}

?>


This code will print a pyramid of stars, with 5 rows. The first while loop controls the number of rows, while the second while loop controls the number of stars in each row. The first while loop starts with $i set to 1, and it will continue to execute as long as $i is less than or equal to 5. Inside the first while loop, the second while loop starts with $j set to 1, and it will continue to execute as long as $j is less than or equal to $i. Inside the second while loop, the echo function is called to print a star. After the second while loop terminates, the value of $j is incremented by 1. This process repeats until the value of $j is no longer less than or equal to $i. When this happens, the second while loop terminates. The first while loop then increments the value of $i by 1, and the process repeats. This continues until the value of $i is no longer less than or equal to 5. When this happens, the first while loop terminates, and the code ends.

No comments:

Post a Comment