iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP If…Else

PHP's conditionals are if, elseif (one word) / else if (two), and else.

The shape

PHP
<?php
$x = 7;
if ($x > 10) {
    echo 'big';
} elseif ($x > 5) {
    echo 'mid';
} else {
    echo 'small';
}

Single-line shorthand — the ternary

PHP
$tier = $score >= 90 ? 'gold'
      : ($score >= 70 ? 'silver'
      : 'bronze');

Useful for short choices. Avoid deeply nesting — pull into an if/elseif chain or a match.

Templating syntax

In view files, the alternative syntax is easier to read than braces:

PHP
<?php if ($user->isAdmin()): ?>
    <a href="/admin">Admin</a>
<?php elseif ($user->isMember()): ?>
    <a href="/account">Account</a>
<?php else: ?>
    <a href="/login">Log in</a>
<?php endif; ?>

Truthiness

PHP treats these as false:

  • false, null
  • 0, 0.0, '0', ''
  • Empty array []

Everything else is true — including the string 'false'!

Common smells

BadBetter
if ($x == true)if ($x)
if (strlen($s) > 0)if ($s !== '')
Deeply nested ifsEarly return for the happy path.
Tip: If you find a long if-chain comparing one variable to multiple values, see if match (PHP 8.0+) reads better.

Example

Example
<?php
$x = 7;
if ($x > 10) {
    echo 'big';
} elseif ($x > 5) {
    echo 'mid';
} else {
    echo 'small';
}
Try it Yourself »

Exercise

Second-branch keyword.

if ($x > 10) {} ($x > 5) {} else {}

Test yourself

Q1. PHP truthiness — which is FALSY?
Q2. Template-friendly endif syntax uses…
Q3. Long if-chains testing one value are usually replaced by…

Discussion

Loading…