Thursday 15 April 2021

Php: while loop

while loop executes a block of statements until a particular condition is true

 

Syntax

while (expression) {
      //statements
}

 

The expression in the while statement must evaluates to a boolean value, otherwise compiler will throw error. While statement first evaluates the expression, until the expression evaluates to true, it  executes the code inside the while block, otherwise it comes out of the while loop.

 

Example 1: Printing numbers from 0 to 9.

$i = 0;
while($i < 10){
    echo "i = $i\n";
    $i++;
}

 

Example 2: Printing numbers from 9 to 0.

$i=9;
while($i >= 0)
{
    echo "i = $i\n";
    $i--;
}

Example 3: Printing elements of array.

$arr1 = [
    2,
    3,
    'Hello',
    true
];

$i=0;
while($i < count($arr1)){
    echo "arr1[$i] : $arr1[$i]\n";
    $i++;
}


Find the below working application.

 

while_loop_demo.php

#!/usr/bin/php

<?php
echo "Printing numbers from 0 to 9\n";
$i = 0;
while($i < 10){
    echo "i = $i\n";
    $i++;
}


echo "\n\nPrinting values from 9 to 0\n";
$i=9;
while($i >= 0)
{
    echo "i = $i\n";
    $i--;
}

echo "\nElements of array: \n";
$arr1 = [
    2,
    3,
    'Hello',
    true
];

$i=0;
while($i < count($arr1)){
    echo "arr1[$i] : $arr1[$i]\n";
    $i++;
}

?>


Output

$./while_loop_demo.php 

Printing numbers from 0 to 9
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9


Printing values from 9 to 0
i = 9
i = 8
i = 7
i = 6
i = 5
i = 4
i = 3
i = 2
i = 1
i = 0

Elements of array: 
arr1[0] : 2
arr1[1] : 3
arr1[2] : Hello
arr1[3] : 1









 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment