Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 147 ยท Control Flow

if, elseif and else

Learn PHP if, elseif and else - how conditions are evaluated, chains of checks, nesting, the alternative syntax for HTML templates, and the classic if-statement mistakes.

Until now, every script you've written ran from the first line to the last, the same way every time. Real programs make decisions: show the checkout button only when the cart has items, charge shipping only below a certain total, greet a logged-in user by name. The if statement is how PHP decides whether to run a block of code.

This lesson starts the Control Flow chapter. You'll learn if, else and elseif, how PHP turns any condition into true or false, how to keep chains of checks readable, the alternative if: ... endif; syntax used in HTML templates, and the mistakes that trip up beginners and experienced developers alike. You'll use the comparison and logical operators from the previous chapter in nearly every example.

The if statement

An if statement has a condition in parentheses and a block of code in braces. PHP evaluates the condition, and if it's true, runs the block. If it's false, PHP skips the block and carries on after the closing brace:

PHP
if (condition) {
    // runs only when the condition is true
}
PHP A first if statement

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.

Change $cartTotal to 60 and run it again: the first message appears and the second disappears. The last echo runs either way, because it's outside both blocks.

Conditions are converted to booleans

The condition doesn't have to be a comparison. PHP converts whatever value you give it to true or false, using the rules from Booleans and null. The falsy values are false, 0, 0.0, '', '0', null and the empty array []; everything else is truthy:

PHP Truthy and falsy conditions

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.

The surprises are ' ' (a space is a real character, so it's truthy), [0] (an array with one element, even if that element is falsy) and the string 'false' (any non-empty string except '0' is truthy). Relying on truthiness is fine for simple checks like "does this array have elements?", but when the difference between 0, '' and null matters, compare explicitly: if ($count === 0), if ($name !== ''), if ($user !== null).

Note: The loop in that example is a foreach, which runs the block once for each element of an array. You'll learn it properly in foreach Loops.

Always use braces

PHP lets you leave out the braces when the block is a single statement:

PHP
if ($isAdmin) echo 'Welcome, admin';   // legal, but avoid

Don't. Without braces, only the very next statement belongs to the if. The moment someone adds a second line, it runs unconditionally, even though the indentation suggests otherwise. The PSR-12 and PER coding styles (see Coding Standards and PSRs) require braces on every control structure, and so does every example in this tutorial.

else: the other branch

Add an else block to run code when the condition is false. Exactly one of the two blocks runs:

PHP Choosing between two paths

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.

This example reads a line of input with fgets(STDIN). The Input box under the editor already contains 17; change it and run again. trim() removes the line break at the end of the input, and (int) converts the text to a number (see Type Juggling and Casting). Because the input isn't echoed automatically, the script prints the number itself so the output reads naturally.

elseif: more than two choices

When there are several possibilities, chain them with elseif. PHP tests each condition from the top and runs the first block whose condition is true. It then skips everything else in the chain, and the optional final else catches whatever no condition matched:

PHP Grading with elseif

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.

The order of the checks matters. A score of 97 is also >= 80 and >= 70, but the chain stops at the first match, so it gets an A. If you reversed the order and tested >= 60 first, every passing score would be a D. When conditions overlap, put the most specific one first.

elseif or else if?

With braces, you can also write else if (two words). PHP reads it as an else whose block is another if statement, and the result is identical. The PSR-12 style asks for the one-word elseif, and in the alternative syntax below only elseif works, so make it a habit.

Nesting and combining conditions

You can put an if inside another if. A little nesting is natural, but each level makes the code harder to follow. Often you can combine conditions with && and || instead:

PHP Nested versus combined conditions

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.

In the last condition, the parentheses group the two shipping rules so that $total > 50 applies to both. && binds more tightly than ||, so without them the meaning would change. Thanks to short-circuiting, PHP stops evaluating as soon as the answer is known: if $total > 50 is false, in_array() is never called.

When nesting gets deep anyway, the usual fix is to handle the unusual cases first and leave early (with return inside a function, or continue inside a loop). That technique, called guard clauses, is covered in break, continue and Loop Control.

The alternative syntax for templates

PHP is often mixed with HTML, and closing braces scattered between HTML tags are hard to match up. For templates, PHP offers an alternative syntax: replace the opening brace with a colon and the closing brace with endif;:

PHP
<?php if ($cartCount === 0): ?>
    <p>Your cart is empty.</p>
<?php elseif ($cartCount === 1): ?>
    <p>You have one item in your cart.</p>
<?php else: ?>
    <p>You have <?= $cartCount ?> items in your cart.</p>
<?php endif; ?>

Everything outside the <?php ... ?> tags is sent to the browser as-is, but only for the branch that matches. The <?= short echo tag from PHP Syntax prints a value. In the alternative syntax you must write elseif as one word; else if: is a parse error.

You can run a template in the editor too. The output is the HTML source as text; on a web server, the browser would render it as a page:

PHP An if block inside an HTML template

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.

htmlspecialchars() turns the < and > in the name into &lt; and &gt;, so a user can't inject HTML into your page. Escape every value you print into HTML, as explained in PHP and HTML Templates and Preventing XSS. Keep the brace syntax for normal code; the alternative syntax is for files that are mostly HTML.

Common mistakes

Assignment instead of comparison

One = assigns; == and === compare. Inside a condition, a single = stores the value and then tests it, so this check is always true for any truthy value:

PHP The single equals sign bug

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.

The first block grants access and silently changes $role to 'admin'. Static analysis tools catch this, and some developers write "Yoda conditions" such as 'admin' === $role so that a missing = becomes a syntax error. Using === everywhere and reading your conditions carefully works just as well.

A semicolon after the condition

PHP
if ($stock === 0); {
    echo 'Sold out';   // ALWAYS runs
}

The semicolon ends the if statement with an empty body, and the block below is just a block that always runs. There's no error message, so this bug can hide for a long time.

Truthiness where 0 is a valid answer

Some functions return 0 as a valid result and false for "not found". strpos() is the classic example: it returns the position of a substring, and position 0 is falsy:

PHP strpos and the zero position

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.

Compare against false with !==, or better, use str_contains(), str_starts_with() and str_ends_with() (PHP 8.0), which return a real boolean. The same caution applies to empty(), which treats '0' as empty: a user who types the number zero into a form would be told the field is required.

Loose comparisons

== converts types before comparing. PHP 8 made this much saner ('abc' == 0 is now false), but surprises remain, such as '1e3' == '1000' being true because both look numeric. Prefer === in conditions unless you deliberately want conversion; Comparison Operators has the full table.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? $n = 15; if ($n > 10) { echo "A"; } elseif ($n > 5) { echo "B"; } else { echo "C"; }

    The chain runs only the first block whose condition is true. 15 > 10, so it prints A and skips the rest.
  2. 2. Which of these values makes if ($value) run its block?

    A string with a space is non-empty and not '0', so it's truthy. '0', the empty array and 0.0 are all falsy.
  3. 3. What is wrong with if ($status = "paid") { ship(); }?

    A single = is assignment. The assigned string is truthy, so the block always runs and $status is overwritten. Use ===.
  4. 4. In the alternative template syntax, how do you close an if block?

    The alternative syntax uses if (...):, elseif (...):, else: and endif;.
  5. 5. Why does if (strpos('apple pie', 'apple')) take the false branch?

    Position 0 is a valid result but falsy. Compare with !== false or use str_contains().

Summary

  • if (condition) { ... } runs a block only when the condition is true; PHP converts any value to a boolean using the truthy/falsy rules.
  • else runs when the condition is false; elseif adds more conditions, and the first true one wins, so order overlapping checks from most to least specific.
  • Always use braces, and write elseif as one word.
  • Combine conditions with && and || instead of deep nesting, and add parentheses when mixing them.
  • In templates, use the alternative syntax if (...): ... elseif (...): ... else: ... endif; and escape output with htmlspecialchars().
  • Watch for = instead of ===, a stray semicolon after the condition, and functions like strpos() that return 0 as a valid result.

Next: switch and match