Sunday 18 April 2021

Php: do-while loop

do-while is a loop construct like while, but evaluates its expression at the bottom of the loop instead of the top.

 

Syntax

do {
    //statement(s)
} while (expression);

 

Example 1: Print numbers from 0 to 9.

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

 

Example 2: Print numbers from 9 to 0.

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

 

Example 3: Print elements of array.

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

 

Find the below working application.

 

do_while_demo.php

#!/usr/bin/php

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

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

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

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

 

Output

$./do_while_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