HOME HTML EDITOR C JAVA PHP

PHP If...Else...Elseif Statements

Conditional statements are used to perform different actions based on different conditions. In PHP, we have several conditional statements that allow our code to make decisions.

1. The if Statement

The if statement executes some code only if a specified condition is true.

<?php
  $t = 14;

  if ($t < 20) {
    echo "Have a good day!";
  }
?>

2. The if...else Statement

The if...else statement executes some code if a condition is true and another code if that condition is false.

<?php
  $t = 22;

  if ($t < 20) {
    echo "Have a good day!";
  } else {
    echo "Have a good night!";
  }
?>

3. The if...elseif...else Statement

The if...elseif...else statement is used to test more than two conditions.

<?php
  $t = 10;

  if ($t < 10) {
    echo "Have a good morning!";
  } elseif ($t < 20) {
    echo "Have a good day!";
  } else {
    echo "Have a good night!";
  }
?>

4. Short Hand If (Ternary Operator)

PHP also provides a shorthand way of writing if statements using the ? and : operators.

<?php
  $age = 18;
  $status = ($age >= 18) ? "Adult" : "Minor";
  echo $status;
?>
Note: In the if...elseif structure, as soon as one condition is found to be TRUE, PHP executes the corresponding block and skips the rest of the conditions.