PHP If..Else Condition Example

Apr 08, 2021 . Admin

Hello Friends,

Now In this blog you'll learn how to write decision-making code using if...else...elseif statements in PHP. Like most programming languages, PHP additionally sanctions you to write code that perform different actions predicated on the results of a logical or comparative test conditions at run time. This means, you can engender test conditions in the form of expressions that evaluates to either true or false and predicated 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...elseif....else statement
  • The if...else statement

The if Statement

if statement - executes some code if one condition is true

Syntax:
if(condition){
    // Code to be executed
}
Example : if Statement
<?php

  $d = date("D");  // Where "D" - A textual representation of a day (three letters)
     
    if ($d == "Thu")
       echo "Have a nice weekend!";

    else
       echo "Have a nice day!";

?>
Output
Have a nice weekend!

Now, Let's see another example of if..else statement..

Example : if Statement
<?php

$no=10;

    if(($no%2)==0)
    {
        echo 'The number '.$no.' is even.';
    }
    else
    {
        echo 'The number '.$no.' is odd.';
    }

?>
Output
The number is even.  

The else..if Statement

if...elseif...else statement - executes different codes for more than two conditions

Syntax:
if (condition)
   code to be executed if condition is true;
elseif (condition)
   code to be executed if condition is true;
else
   code to be executed if condition is false;

The following example will output "Have a nice weekend!" if the current day is Thursday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise, it will output "Have a nice day!" −

Example : if...elseif....else
<?php

   $d = date("D");  // Where "D" - A textual representation of a day (three letters)
     
     if ($d == "Thu")
        echo "Have a nice weekend!";
     
     elseif ($d == "Sun")
        echo "Have a nice Sunday!"; 
     
     else
        echo "Have a nice day!"; 

?>
Output
Have a nice weekend!

It will help you..

#PHP