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

Posted by TotalDC

Now that we covered constants, strings and logic operators in PHP, maybe its 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 perform different actions based on the results of comparison results of given values. This means that you can create test conditions that returns 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 is used to execute 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 simple if statement is enough sometimes, other times you must include alternative choice through adding 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 cimbine 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 of 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 ternary operator could look like this:

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: