Controll Statement

By ukmodak | March 31st 2024 10:36:23 AM | viewed 484 times

if Statement:

PHP if else statement is used to test condition. There are various ways to use if statement in PHP.

  1. if
  2. if-else
  3. if-else-if
  4. nested if
if

PHP if statement allows conditional execution of code. It is executed if condition is true.If statement is used to executes the block of code exist inside the if statement only if the specified condition is true.

$num =12;  
if($num <100){  
	echo "$num is less than 100";  
}  

op:12 is less than 100
 
If-else Statement

PHP if-else statement is executed whether condition is true or false.If-else statement is slightly different from if statement. It executes one block of code if the specified condition is true and another block of code if the condition is false.

$num=12;  
if($num%2==0){  
echo "$num is even number";  
}else{  
echo "$num is odd number";  
}  

op:12 is even number
If-else-if Statement

The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can check multiple conditions using this statement.

$marks=69;      
    if ($marks<33){    
        echo "fail";    
    }    
    else if ($marks>=34 && $marks<50) {    
        echo "D grade";    
    }    
    else if ($marks>=50 && $marks<65) {    
       echo "C grade";   
    }    
    else if ($marks>=65 && $marks<80) {    
        echo "B grade";   
    }    
    else if ($marks>=80 && $marks<90) {    
        echo "A grade";    
    }  
    else if ($marks>=90 && $marks<100) {    
        echo "A+ grade";   
    }  
   else {    
        echo "Invalid input";    
    } 

op:B Grade
nested if Statement

The nested if statement contains the if block inside another if block. The inner if statement executes only when specified condition in outer if statement is true.

$age = 23;  
$nationality = "Indian";  
  //applying conditions on nationality and age  
if ($nationality == "Indian")  
{  
	if ($age >= 18) {  
		echo "Eligible to give vote";  
	}  
	else {    
		echo "Not eligible to give vote";  
	}  
}

op:Eligible to give vote  

Switch Statement

PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.

Syntax
    switch(expression){      
    case value1:      
     //code to be executed  
     break;  
    case value2:      
     //code to be executed  
     break;  
    ......      
    default:       
     code to be executed if all cases are not matched;    
    }  
Important points to be noticed about switch case:
  • The default is an optional statement. Even it is not important, that default must always be the last statement.
  • There can be only one default in a switch statement. More than one default may lead to a Fatal error.
  • Each case can have a break statement, which is used to terminate the sequence of statement.
  • The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
  • PHP allows you to use number, character, string, as well as functions in switch expression
  • Nesting of switch statements is allowed, but it makes the program more complex and less readable.
  • You can use semicolon (;) instead of colon (:). It will not generate any error.
$num=20;      
switch($num){      
case 10:      
echo("number is equals to 10");      
break;      
case 20:      
echo("number is equal to 20");      
break;      
case 30:      
echo("number is equal to 30");      
break;      
default:      
echo("number is not equal to 10, 20 or 30");      
}     

op:number is equal to 20
PHP switch statement is fall-through

PHP switch statement is fall-through. It means it will execute all statements after getting the first match, if break statement is not found.

$ch = 'c';  
    switch ($ch)  
    {     
        case 'a':   
            echo "Choice a";  
            break;  
        case 'b':   
            echo "Choice b";  
            break;  
        case 'c':   
            echo "Choice c";      
            echo "
"; case 'd': echo "Choice d"; echo "
"; default: echo "case a, b, c, and d is not found"; } op: Choice c Choice d case a, b, c, and d is not found
nested switch statement

Nested switch statement means switch statement inside another switch statement. Sometimes it leads to confusion.

$car = "Hyundai";                   
        $model = "Tucson";    
        switch( $car )    
        {    
            case "Honda":    
                switch( $model )     
                {    
                    case "Amaze":    
                           echo "Honda Amaze price is 5.93 - 9.79 Lakh.";   
                        break;    
                    case "City":    
                           echo "Honda City price is 9.91 - 14.31 Lakh.";    
                        break;     
                }    
                break;    
            case "Renault":    
                switch( $model )     
                {    
                    case "Duster":    
                        echo "Renault Duster price is 9.15 - 14.83 L.";  
                        break;    
                    case "Kwid":    
                           echo "Renault Kwid price is 3.15 - 5.44 L.";  
                        break;    
                }    
                break;    
            case "Hyundai":    
                switch( $model )     
                {    
                    case "Creta":    
                        echo "Hyundai Creta price is 11.42 - 18.73 L.";  
                        break;    
        case "Tucson":    
                           echo "Hyundai Tucson price is 22.39 - 32.07 L.";  
                        break;   
                    case "Xcent":    
                           echo "Hyundai Xcent price is 6.5 - 10.05 L.";  
                        break;    
                }    
                break;     
        }

op:Hyundai Tucson price is 22.39 - 32.07 L.		

For Loop

PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when you already know how many times you want to execute a block of code.

Syntax
     for(initialization; condition; increment/decrement){  
    //code to be executed  
    }  
 
  • initialization - Initialize the loop counter value. The initial value of the for loop is done only once. This parameter is optional.
  • condition - Evaluate each iteration value. The loop continuously executes until the condition is false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.
  • Increment/decrement - It increments or decrements the value of the variable.
 for($n=1;$n<=10;$n++){    
echo "$n
"; } op:

All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass parameters, it will execute infinite.

  $i = 1;  
    //infinite loop  
    for (;;) {  
        echo $i++;  
        echo "
"; }

Below is the example of printing numbers from 1 to 9 in four different ways using for loop.

 /* example 1 */  
  
    for ($i = 1; $i <= 9; $i++) {  
    echo $i;  
    }  
    echo "
"; /* example 2 */ for ($i = 1; ; $i++) { if ($i > 9) { break; } echo $i; } echo "
"; /* example 3 */ $i = 1; for (; ; ) { if ($i > 9) { break; } echo $i; $i++; } echo "
"; /* example 4 */ for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++); op: 123456789 123456789 123456789 123456789
Nested For Loop
 for($i=1;$i<=3;$i++){
 
   for($j=1;$j<=3;$j++){    
      echo "$i   $j
"; } } op: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3

foreach loop

The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the variables of different datatype.

The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.

Syntax
   foreach ($array as $value) {  
        //code to be executed  
    }  
	
	There is one more syntax of foreach loop.
	
  foreach ($array as $key => $element) {   
        //code to be executed  
    }  
 
 
 PHP program to print array elements using foreach loop.
 
 
  $season = array ("Summer", "Winter", "Autumn", "Rainy");  
      
    //access array elements using foreach loop  
    foreach ($season as $element) {  
        echo "$element";  
        echo "
"; } op: Summer Winter Autumn Rainy PHP program to print associative array elements using foreach loop. //declare array $employee = array ( "Name" => "Alex", "Email" => "alex_jtp@gmail.com", "Age" => 21, "Gender" => "Male" ); //display associative array element through foreach loop foreach ($employee as $key => $element) { echo $key . " : " . $element; echo "
"; } op: Name : Alex Email : alex_jtp@gmail.com Age : 21 Gender : Male Multi-dimensional array //declare multi-dimensional array $a = array(); $a[0][0] = "Alex"; $a[0][1] = "Bob"; $a[1][0] = "Camila"; $a[1][1] = "Denial"; //display multi-dimensional array elements through foreach loop foreach ($a as $e1) { foreach ($e1 as $e2) { echo "$e2\n"; } } op:Alex Bob Camila Denial Dynamic array //dynamic array foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) { echo "$elements\n"; } op:j a v a t p o i n t

While Loop

PHP while loop can be used to traverse set of code like for loop. The while loop executes a block of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from the body of loop.

It should be used if the number of iterations is not known.

The while loop is also called an Entry control loop because the condition is checked before entering the loop body. This means that first the condition is checked. If the condition is true, the block of code will be executed.

Syntax
 while(condition){  
  //code to be executed  
 } 
 
 //Alternative Syntax
 
while(condition):  
    //code to be executed  
      
endwhile;  
 
$n=1;    
while($n<=10){    
echo "$n
"; $n++; } op: Alternative Example $n=1; while($n<=10): echo "$n
"; $n++; endwhile; op: //Below is the example of printing alphabets using while loop. $i = 'A'; while ($i < 'H') { echo $i; $i++; echo "
"; } op: A B C D E F G
Nested While Loop

We can use while loop inside another while loop in PHP, it is known as nested while loop.

In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer while loop is to be executed for 3 times and nested while loop for 3 times, nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).

$i=1;    
while($i<=3){    
$j=1;    
while($j<=3){    
echo "$i   $j
"; $j++; } $i++; } op: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
Infinite While Loop

If we pass TRUE in while loop, it will be an infinite loop.

Syntax
while(true) {    
//code to be executed    
}   
 while (true) {  
	echo "Hello Javatpoint!";  
	echo "
"; }

do-while loop

PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at least once.

The PHP do-while loop is used to execute a set of code of the program several times. If you have to execute the loop at least once and the number of iterations is not even fixed, it is recommended to use the do-while loop.It executes the code at least one time always because the condition is checked after executing the code. The do-while loop is very much similar to the while loop except the condition check. The main difference between both loops is that while loop checks the condition at the beginning, whereas do-while loop checks the condition at the end of the loop.

Syntax
do{  
  //code to be executed  
}while(condition);  
$n=1;    
do{    
echo "$n
"; $n++; }while($n<=10);

A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-while loop, it is must that the program should not contain any other statements after the do-while loop. In this case, it will not generate any error.

 $x = 5;  
    do {  
        echo "Welcome to javatpoint! 
"; $x++; } while ($x < 10); op: Welcome to javatpoint! Welcome to javatpoint! Welcome to javatpoint! Welcome to javatpoint! Welcome to javatpoint!

The following example will increment the value of $x at least once. Because the given condition is false.

$x = 1;  
    do {  
        echo "1 is not greater than 10.";  
        echo "
"; $x++; } while ($x > 10); echo $x; op: 1 is not greater than 10. 2
Difference between while and do-while loop
while Loop do-while loop
The while loop is also named as entry control loop. The do-while loop is also named as exit control loop.
The body of the loop does not execute if the condition is false. The body of the loop executes at least once, even if the condition is false.
Condition checks first, and then block of statements executes. Block of statements executes first and then condition checks.
This loop does not use a semicolon to terminate the loop. Do-while loop use semicolon to terminate the loop.

Break

PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only.

The break keyword immediately ends the execution of the loop or switch structure. It breaks the current flow of the program at the specified condition and program control resumes at the next statements outside the loop.

The break statement can be used in all types of loops such as while, do-while, for, foreach loop, and also with switch case.

Syntax
    jump statement;  
    break;  
Break: inside loop
for($i=1;$i<=10;$i++){    
echo "$i 
"; if($i==5){ break; } } op: 1 2 3 4 5
Break: inside inner loop
for($i=1;$i<=3;$i++){    
 for($j=1;$j<=3;$j++){    
  echo "$i   $j
"; if($i==2 && $j==2){ break; } } } op: 1 1 1 2 1 3 2 1 2 2 3 1 3 2 3 3
Break: inside switch statement
$num=200;        
switch($num){        
case 100:        
echo("number is equals to 100");        
break;        
case 200:        
echo("number is equal to 200");        
break;        
case 50:        
echo("number is equal to 300");        
break;        
default:        
echo("number is not equal to 100, 200 or 500");        
}   

op:
number is equal to 200    
Break: with array of string
//declare an array of string  
$number = array ("One", "Two", "Three", "Stop", "Four");  
foreach ($number as $element) {  
	if ($element == "Stop") {  
	break;  
	}  
   echo "$element 
"; } op: One Two Three
Break: switch statement without break

It is not essential to break out of all cases of a switch statement. But if you want that only one case to be executed, you have to use break statement.

$car = 'Mercedes Benz';  
switch ($car) {    
default:  
echo '$car is not Mercedes Benz
'; case 'Orange': echo '$car is Mercedes Benz'; } op: $car is not Mercedes Benz $car is Mercedes Benz
Break: using optional argument

The break accepts an optional numeric argument, which describes how many nested structures it will exit. The default value is 1, which immediately exits from the enclosing structure.

$i = 0;  
while (++$i) {  
    switch ($i) {  
        case 5:  
            echo "At matched condition i = 5
\n"; break 1; // Exit only from the switch. case 10: echo "At matched condition i = 10; quitting
\n"; break 2; // Exit from the switch and the while. default: break; } } op: At matched condition i = 5 At matched condition i = 10; quitting

continue statement

The PHP continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.

The continue statement is used within looping and switch control structure when you immediately jump to the next iteration.

The continue statement can be used with all types of loops such as - for, while, do-while, and foreach loop. The continue statement allows the user to skip the execution of the code for the specified condition.

Syntax
    jump-statement;  
    continue;  
Continue Example with for loop

In the following example, we will print only those values of i and j that are same and skip others.

//outer loop  
    for ($i =1; $i<=3; $i++) {  
        //inner loop  
        for ($j=1; $j<=3; $j++) {  
            if (!($i == $j) ) {  
                continue;       //skip when i and j does not have same values  
            }  
            echo $i.$j;  
            echo "
"; } } op: 11 22 33
continue Example in while loop

In the following example, we will print the even numbers between 1 to 20.

//php program to demonstrate the use of continue statement  
  
    echo "Even numbers between 1 to 20: 
"; $i = 1; while ($i<=20) { if ($i %2 == 1) { $i++; continue; //here it will skip rest of statements } echo $i; echo "
"; $i++; } op: Even numbers between 1 to 20: 2 4 6 8 10 12 14 16 18 20
continue Example with array of string

The following example prints the value of array elements except those for which the specified condition is true and continue statement is used.

  $number = array ("One", "Two", "Three", "Stop", "Four");  
    foreach ($number as $element) {  
        if ($element == "Stop") {  
            continue;  
        }  
        echo "$element 
"; } op: One Two Three Four
continue Example with optional argument

The continue statement accepts an optional numeric value, which is used accordingly. The numeric value describes how many nested structures it will exit.

//outer loop  
    for ($i =1; $i<=3; $i++) {  
        //inner loop  
        for ($j=1; $j<=3; $j++) {  
            if (($i == $j) ) {      //skip when i and j have same values  
                continue 1;     //exit only from inner for loop   
            }  
            echo $i.$j;  
            echo "
"; } } op: 12 13 21 23 31 32
bONEandALL
Visitor

Total : 26654

Today :3

Today Visit Country :

  • France
  • United States