PHP While Loop


PHP While Loop

In this tutorial, we will learn about while loop in PHP. We will cover the basics of iterative execution using while loops.


What is a While Loop

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop runs as long as the condition evaluates to true.


Syntax

The syntax for the while loop in PHP is:

while (condition) {
    // Code block to be executed
}

The while loop evaluates the condition before executing the loop's body. If the condition is true, the code block inside the loop is executed. This process repeats until the condition becomes false.



Printing Numbers from 1 to 5

  1. Declare a variable $i and initialize it to 1.
  2. Use a while loop to print numbers from 1 to 5.

PHP Program

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

Output

1
2
3
4
5


Calculating the Sum of First N Natural Numbers

  1. Declare variables $n and $sum.
  2. Assign a value to $n.
  3. Initialize $sum to 0.
  4. Use a while loop to calculate the sum of the first $n natural numbers.
  5. Print the sum.

PHP Program

<?php
$n = 10;
$sum = 0;
$i = 1;
while ($i <= $n) {
    $sum += $i;
    $i++;
}
echo "Sum of first $n natural numbers is $sum\n";
?>

Output

Sum of first 10 natural numbers is 55


Reversing a Number

  1. Declare variables $num and $rev.
  2. Assign a value to $num.
  3. Initialize $rev to 0.
  4. Use a while loop to reverse the digits of $num.
  5. Print the reversed number.

PHP Program

<?php
$num = 12345;
$rev = 0;
while ($num != 0) {
    $digit = $num % 10;
    $rev = $rev * 10 + $digit;
    $num = (int)($num / 10);
}
echo "Reversed number is $rev\n";
?>

Output

Reversed number is 54321