Monday 19 April 2021

Php: break statement: exit from the loop

‘break’ statement is used to come out of the loop.

 

Syntax

break;

 

Example 1: Printing numbers from 1 to 5.

for ($i = 0; $i < 10; $i ++) {
    echo "i = $i\n";
    if($i == 5){
        break;
    }
}

 

Example 2: Printing stars in triangle shape.

for($i=0; $i<10; $i++){
    for($j=0; $j<10; $j++){
        if($j > $i){
            break;
        }
        echo"* ";
    }
    echo"\n";
}

break_statement_demo.php

#!/usr/bin/php

<?php
echo "Printing numbers from 0 to 5\n";
for ($i = 0; $i < 10; $i ++) {
    echo "i = $i\n";
    if($i == 5){
        break;
    }
}

echo "\n\nPrinting stars in triangle shape\n";

for($i=0; $i<10; $i++){
    for($j=0; $j<10; $j++){
        if($j > $i){
            break;
        }
        echo"* ";
    }
    echo"\n";
}

?>


Output

$./break_statement_demo.php 

Printing numbers from 0 to 5
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5


Printing stars in triangle shape
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * * 
* * * * * * * * * *





 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment