PHP IF – ELSE Statements. Everything You Need To Know About

Posted by TotalDC

Now that we have covered constants, strings, and logic operators in PHP, maybe it’s time to learn about PHP if – else statements.

PHP Conditional Statements

As you may guess, PHP like other programming languages lets you write code that performs different actions based on the comparison results of given values. This means that you can create test conditions that return true or false and based on that 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 IF Statement

The if statement executes a block of code if the condition returns true. The following example will output “Have a nice day!” if the current day is Friday:

<?php
$day = date("D");
if($day == "Fri"){
    print "Have a nice weekend!";
}
?>

The IF-ELSE Statement

While a simple if statement is enough sometimes, other times you must include 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 condition returns true and another if it returns false. The following example will output “Have a nice weekend!” if the current day is Friday, otherwise, it will output “Have a nice day!”

<?php
$day = date("D");
if($day == "Fri"){
    print "Have a nice weekend!";
} else{
    print "Have a nice day!";
}
?>

The IF-ELSEIF-ELSE Statement

The if-elseif-else is a statement that is used to combine multiple if-else statements. The following example will output “Have a nice weekend!” if the current day is Friday, and “Have a nice Monday!” if the current day is Sunday, otherwise, it will output “Have a nice day!”

<?php
$day = date("D");
if($day == "Fri"){
    print "Have a nice weekend!";
} elseif($d == "Mon"){
    print "Have a nice Monday!";
} else{
    print "Have a nice day!";
}
?>

Bonus. The Ternary Operator

What is the ternary operator you may be asking? The ternary operator simply is a shorthand for writing if-else statements. The ternary operator is represented by the question mark (?) symbol and it takes three operands: a condition check, a result (true or false), and the results for true and result for false. The example for a ternary operator could look like this:

<?php print ($age < 18) ? 'Legal' : 'Adult'; ?>