PHP ยท Chapter 13 of 44

PHP If...Else

Conditional statements let your program make decisions and run different code depending on whether a condition is true or false. The if statement runs a block of code if its condition is true.

You can extend this with else to run code when the condition is false, and elseif to check multiple conditions in sequence, stopping at the first one that is true.

Syntax
if (condition) {
  // code
} elseif (condition2) {
  // code
} else {
  // code
}

if, elseif, else

if checks a condition; elseif checks another condition if the previous ones were false; else runs when none of the previous conditions were true.

The ternary operator

The shorthand ternary operator (condition ? value1 : value2) lets you write simple if/else logic as a compact expression.

Example 1 (php)
<?php
  $age = 20;
  if ($age >= 18) {
    echo "Adult";
  } else {
    echo "Minor";
  }
?>
Output
Adult

Since $age is 20, which is >= 18, the if block runs and prints "Adult".

Example 2 (php)
<?php
  $score = 75;
  echo $score >= 60 ? "Pass" : "Fail";
?>
Output
Pass

The ternary operator is a compact way to write a simple if/else expression.

Key points

  • if runs code when a condition evaluates to true.
  • elseif checks additional conditions in order.
  • else runs when no previous condition was true.
  • The ternary operator ?: is a shorthand for simple if/else logic.
๐Ÿ’ก Note: Use elseif (one word) in PHP rather than else if inside a chain, although both work identically.

๐Ÿ“ Quick Quiz

1. Which keyword checks an additional condition after if?

2. What does the ternary operator provide?

3. When does the else block run?