Making Decisions with if and else

Different visitors, different pages

8 min read

Everything you have written so far runs the same way every time. But the whole point of a dynamic website is that it reacts. Logged in? Show the dashboard. Out of stock? Hide the buy button. Past midnight? Say Good evening. The tool for reacting is the if statement.

The basic if

<?php
$stock = 5;
if ($stock > 0) {
    echo "In stock, order now!";
}
?>

Read it like English: if the stock is greater than zero, do the stuff between the curly braces. The part in parentheses is called the condition, and it is always a question with a yes or no answer. If the answer is yes, the braces run. If no, PHP skips straight past them.

Adding an else

Often you want a plan B:

<?php
$stock = 0;
if ($stock > 0) {
    echo "In stock, order now!";
} else {
    echo "Sorry, sold out.";
}
?>

Exactly one of the two blocks runs, never both, never neither. With $stock = 0, the condition is false, so this prints Sorry, sold out.

More than two paths: elseif

<?php
$stock = 3;
if ($stock > 10) {
    echo "In stock";
} elseif ($stock > 0) {
    echo "Only a few left!";
} else {
    echo "Sold out";
}
?>

PHP checks the conditions top to bottom and runs the first one that is true, then skips the rest. Here 3 is not greater than 10, but it is greater than 0, so the middle block wins and prints Only a few left!

The comparison toolbox

  • > greater than, < less than
  • >= at least, <= at most
  • == equal to
  • != not equal to
  • === equal in value and in type

That last pair deserves a closer look. A single = puts a value into a variable; a double == asks whether two things are equal. Mixing them up is a classic bug: if ($age = 18) quietly sets age to 18 instead of checking it. The triple === is stricter than ==: it also insists both sides are the same type, so the number 0 and the string "0" count as different. Experienced PHP developers reach for === by default because it avoids surprises, and it is a good habit for you to copy.

Combining conditions

<?php
$stock = 5;
$price = 12.50;
if ($stock > 0 && $price < 20) {
    echo "Affordable and available!";
}
?>

&& means and: both sides must be true. Its sibling || means or: at least one side must be true. With these you can express rules as rich as any real store's business logic.

Memory hook: one equals sign assigns, two compare, three compare strictly. When a condition misbehaves, count your equals signs before anything else.

Quick check

Q1 Which operator checks whether two values are equal, without assigning anything?

Q2 With $stock = 0, what prints? if ($stock > 0) { echo "Available"; } else { echo "Sold out"; }

Want to save your progress? It's free.

Create a free account