php while loop



PHP while loop

PHP while loop used to execute same block of code again and again while a condition is true.

while loop syntax

<?php

while(condition)
{
// block of code to be executed
}

?>

In while loop first check the condition, if condition is true then execute a block of code.

Example of php while loop

<?php

$i=1;
while($i<=5)
{
echo $i;
$i++;
}

?>

The output is:
12345

In above for while example, first set variable $i=1, the condition is $i<=5,
for $i=1 the condition is true then execute code print $i.

Then increment 1 to $i, ,
now $i=2 the condition is true,
$i=3 condition is true,
$i=5 condition is true.
When $i=6 the condition $i<=5 is not true as 6 is not less than or equal to 5.
The while loop true for five times and the result is : 12345

Example

<?php
$i=5;

while($i>0)
{
echo $i;
$i – -;
}

?>

The output is: 54321

Here, we set variable $i=5 and check condition $i>0 after each time decrements 1 to variable $i while a condition is true.

Example – PHP while loop

<?php

$name=”meera”;
$i=1;
while($i<=5)
{
echo “Hello “. $name . “<br/>”;
$i++;
}

?>

The output is:
Hello meera
Hello meera
Hello meera
Hello meera
Hello meera

while loop example

<?php

$i=0;
$sum=0;
while($i<=5)
{
$sum=$sum+$i;
$i++;
}

echo “The sum of 1 to 5 = “.$sum;

?>

The output The sum of 1 to 5 = 15

while loop Example

<?php

$i=1;
while($i<=10)
{
echo $i;
$i=$i+2;
}

?>

The output 13579

Example to display odd and even no of given number using while loop.

<?php

$even=””;
$odd=””;
$i=1;

while($i<=20)
{
if($i%2==0)
{
$even = $even . ” ” .$i ;
}
else
{
$odd = $odd . ” ” .$i;
}

$i++;
}

echo “The Even no = ” . $even .”<br/>”;
echo “The Odd no = ” . $odd;

?>

The output

The Even no = 2 4 6 8 10 12 14 16 18 20
The Odd no = 1 3 5 7 9 11 13 15 17 19

While loop example

<?php

$i=1;

while($i<=5)
{
$j=1;
while($j<=$i)
{
echo $i;
$j++;
}
echo “<br/>”;
$i++;
}

?>

The output is:
1
22
333
4444
55555

Example

<?php

$i=1;
while($i<=5)
{
$j=1;
while($j<=$i)
{
echo $j;
$j++;
}
echo “<br/>”;
$i++;
}

?>

The output is:
1
12
123
12345

PHP while loop example

<?php

$i=1;
while($i<=5)
{
$j=5;

while($j>=$i)
{
echo $j;
$j=$j-1;
}

echo “<br/>”;
$i++;
}

?>

The output is:
54321
5432
543
54
5

Leave a Reply

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