Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Language Constructs and Statements

PHP if, elseif and else

Reference for PHP if, elseif and else: conditional execution, truthiness rules, else if versus elseif, braces and the alternative syntax.

if runs a block of code only when its condition is truthy. You can add any number of elseif branches and one final else. PHP checks the conditions from top to bottom and runs the first branch whose condition is true; the rest are skipped.

The condition is converted to a boolean. Falsy values are false, 0, 0.0, "", "0", [] and null; everything else is truthy.

PHP
if ($score >= 90) {
    echo "A";
} elseif ($score >= 80) {
    echo "B";
} else {
    echo "C or lower";
}

Try it

PHP Choosing a branch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Truthiness and the assignment trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
if (condition) {
    // ...
} elseif (condition) {
    // ...
} else {
    // ...
}

if (condition):
    // ...
elseif (condition):
    // ...
else:
    // ...
endif;
Name Description
condition Any expression. Its value is converted to bool.

Return value: none; if is a statement, not an expression. Use the ternary operator or match when you need a value.

Usage notes

  • Always use braces. A single statement may follow if without braces, but adding a second line later silently falls outside the condition. Coding standards require braces.
  • elseif versus else if. In the brace syntax both behave the same. In the colon syntax you must write elseif as one word.
  • = versus ==. if ($x = 0) assigns and then tests the result. Use === for strict comparisons; see comparison operators.
  • Loose truthiness surprises. "0" is falsy but "0.0" and "false" are truthy. An empty array is falsy. Be explicit ($items !== [], strlen($s) > 0) when it matters.
  • Short-circuiting. && and || stop evaluating as soon as the result is known, so if ($user && $user->isAdmin()) is safe.
  • Early returns (guard clauses) often read better than deep nesting.
  • Template syntax. The colon form with endif; is meant for HTML templates; see alternative syntax.
  • Many equal-value tests are tidier with switch or match.