PHP Conditional Statements

Filter Course


PHP Conditional Statements

Published by: Sujan

Published date: 16 Jun 2021

PHP Conditional Statements - Photo

PHP Conditional Statements

Like most programming languages, PHP conditional statements also allow you to write code that performs different actions based on the results of logical or comparative test conditions at run time. This means you can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions.

There are several statements in PHP that you can use to make decisions:

  • The if statement
  • The if...else statement
  • The if...elseif....else statement
  • The switch...case statement

The if Statement

The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest PHP's conditional statements and can be written like:

if(condition){
// Code to be executed

}

php conditional statements

The if...else Statement

You can enhance the decision-making process by providing an alternative choice by adding an else statement to the if statement. The if...else statement allows you to execute one block of code if the specified condition is evaluated to true and another block of code if it is evaluated to false.

if(condition){
    // Code to be executed if condition is true
} else{
    // Code to  be executed if condition is false

}

 

php conditional statements

The if...elseif...else Statement

The if...elseif...else a special statement that is used to combine multiple if...else statements.

if(condition1){

if(condition1){
// Code to be executed if condition1 is true

} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is
true

} else{
// Code to be executed if both condition1 and condition2 are false

}

php conditional statements

The Ternary Operator (?:)

The ternary operator provides a shorthand way of writing the if...else statements. The ternary operator is represented by the question mark (?) symbol and it takes three operands: a condition to check, a result for true, and a result for false.

php conditional statements

PHP If...Else Vs Switch...Case Switch Case

The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match.

switch(n){
    case label1:
         // Code to be executed if n=label1
         break;
    case label2:
         // Code to be executed if n=label2
         break;
     ...
     default:
          //Code to be executed if n is different from all labels
}
php conditional statements