PHP 8 Condition Control Structures

Control structures are main key of any programming language that permit your script to react differently to different data sources or circumstances. This could permit your content to give different reactions dependent on client input, content, or some other information.

There are the two condition control structures: If and Switch.

If Statement

The if statement is the most commonly used in conditional control statements.
These are the conditions where If statement is used -

To Check Single Expression

Syntax of the if statement

if(condition) { 
 statements;
} 

If the condition in the 'if statement' is true, then the statements enclosed within the curly braces are executed.

Example

<?php
    $i = 5;
    if($i == 5) {
     echo 'Number is 5';
    }
?>

Execute one of two statements based on the condition

In this, if the expression within the if statement is true, then the statements within the if are executed otherwise the statements within the else are executed.

Syntax of the if..else statement

if(condition) { 
 Statement1 
} 
else { 
  Statement2 
}

If the expression in the if statement is true, then statement1 is executed , If the expression in if statement is false, then statement2 is executed.

Example

<?php
    $i = 10;
    if($i == 5) {
     echo 'Number is 5';
    }
    else{
     echo 'Number is not equal to 5'; 
    }
?>




Multiple Conditions

If ...elseif.... else statements are used for more than one conditions.

if(condition1) { 
    Statement1; 
} 
elseif(condition2) { 
    Statement2; 
}
else{ 
    Statement3; 
}

Example

<?php
    if($i < 5) {
     echo 'Number is less than 5';
    }
    elseif($i == 5){
     echo 'Number is 5';
    }
    else{
     echo 'Number is greater than 5'; 
    }
?>




Switch

If there is need to match the value from many different cases and execute the statements within the matched case. Switch statement executes line by line and read all the cases. If the case value is matched with a value passed in the switch expression, then statement within the matched case is executed. We can write break to terminate the execution of further statements, if match case is found.

switch(expression) {
 case value1
    Statement 1;
    break;
  case value2
    Statement 2;
    break;
  Default
    Statement 3;
} 

Example

<?php
$month = 5;
switch($month){
    case 1:
       echo 'Winter Holiday';
       break;
    case 5:
        echo 'Summer Holiday';
        break;
    default:
        echo 'Working Month';
}
?>


Practice Exercises





Read more articles


General Knowledge



Learn Popular Language