PHP Tutorial · Control Flow · Lesson 14 of 38

PHP If Else

Make decisions with if, elseif, else and the ternary operator.

if, elseif, else

Example 1Try it yourself
<?php
$hour = 15;
if ($hour < 12) {
    echo "Good morning\n";
} elseif ($hour < 18) {
    echo "Good afternoon\n";
} else {
    echo "Good evening\n";
}

Output

Good afternoon

Ternary and short ternary

$cond ? $a : $b chooses between two values. The short form $a ?: $b returns $a if it's truthy, otherwise $b.

Example 2Try it yourself
<?php
$stock = 0;
echo $stock > 0 ? "In stock\n" : "Sold out\n";
$nickname = "";
echo ($nickname ?: "Anonymous"), "\n";

Output

Sold out
Anonymous

Alternative syntax in templates

In HTML templates you'll often see the colon syntax, which is easier to read between tags:

<?php if ($user): ?>
  <p>Welcome back, <?= htmlspecialchars($user) ?>!</p>
<?php else: ?>
  <a href="/login">Sign in</a>
<?php endif; ?>

Test yourself

Which keyword adds another condition to an if statement in PHP?

  1. else if only
  2. elseif
  3. elif
  4. orif
Show answer

Answer: elseif