Topic 18 of 48 ยท Full Stack Essentials

echo, if condition (task on if & echo)

Lesson TL;DRTopic 3: echo, if condition (task on if & echo) ๐Ÿ“– 13 min read ยท ๐ŸŽฏ beginner ยท ๐Ÿงญ Prerequisites: phpvariablesintroduction, tablesrowspancolspanmisctagsheadingtagh1h2h6 Why this matters Here's the thin...
13 min readยทbeginnerยทphp ยท echo ยท if-statement ยท conditionals

Topic 3: echo, if condition (task on if & echo)

๐Ÿ“– 13 min read ยท ๐ŸŽฏ beginner ยท ๐Ÿงญ Prerequisites: php-variables-introduction, tables-row-span-col-span-misc-tags-heading-tagh1h2-h6

Why this matters

Here's the thing โ€” up until now, your PHP script just runs top to bottom, doing exactly what you tell it, every single time. It has no opinion. It can't adapt. But real programs need to make choices: if the user is logged in, show their dashboard; if not, show the login page. That's where if comes in. And echo is how your script speaks โ€” how it actually puts words on the screen. Together, these two are the backbone of almost every PHP program you'll ever write. Let's teach your script to think.

What You'll Learn

  • Output text and variable values to the browser with echo
  • Write if, else if, and else blocks to branch program logic
  • Chain multiple independent if checks in a single script
  • Accept user input via an HTML form and drive if logic from $_POST

The Analogy

Think of echo and if as a city hall announcement system with a gatekeeper. The gatekeeper reads a written rule ("if the temperature is above 30 ยฐC, announce a heat advisory"), checks today's actual temperature, and then either speaks the advisory over the loudspeaker โ€” that's echo โ€” or moves on to the next rule. Each rule is independent; the system checks all of them in order. The loudspeaker never decides anything on its own; the gatekeeper (if) does the deciding, and the loudspeaker (echo) does the talking.

Chapter 1: Understanding the Basics

Conditional Statements

PHP provides three closely related keywords for branching:

  • if โ€” executes a block of code when a specified condition is true.
  • else if (also written elseif) โ€” tests a new condition when the preceding if was false.
  • else โ€” executes a fallback block when all preceding conditions were false.

Together they form a decision chain. PHP evaluates each condition top-to-bottom and executes at most one branch.

echo

  • echo โ€” outputs one or more strings to the browser (or terminal). It is a language construct, not a function, so parentheses are optional.
<?php
echo "Hello, Vizag!";
echo "Line one.<br>Line two.";
?>

You can embed a variable directly inside a double-quoted string:

<?php
$city = "Vizag";
echo "Welcome to $city!";   // outputs: Welcome to Vizag!
?>

Single-quoted strings do not interpolate variables โ€” '$city' prints the literal text $city.

Chapter 2: Implementing the Logic โ€” Simple Condition Check

The class's first real task: write a script that tells them whether a number is positive, negative, or zero. This is a three-way branch โ€” exactly what if / else if / else was built for.

<?php
// Define the number
$number = 10;

// Check the condition
if ($number > 0) {
    echo "$number is positive.<br>";
} else if ($number < 0) {
    echo "$number is negative.<br>";
} else {
    echo "$number is zero.<br>";
}
?>

What happens step by step:

  1. PHP evaluates $number > 0. Because 10 > 0 is true, it enters the first block and echoes 10 is positive..
  2. The else if and else branches are skipped entirely.
  3. If $number were -3, the first condition would be false, the else if ($number < 0) would be true, and the second message would print.
  4. If $number were 0, both if and else if would be false, so the else block runs.

Chapter 3: Multiple Independent Conditions

The class wanted more information about the same number: is it odd or even? Is it a multiple of 5? These are separate questions, so they need separate if statements โ€” not more else if branches.

The modulo operator % returns the remainder after division:

  • 10 % 2 โ†’ 0 (even)
  • 7 % 2 โ†’ 1 (odd)
  • 10 % 5 โ†’ 0 (multiple of 5)
  • 7 % 5 โ†’ 2 (not a multiple of 5)
<?php
// Define the number
$number = 10;

// Check if the number is positive, negative, or zero
if ($number > 0) {
    echo "$number is positive.<br>";
} else if ($number < 0) {
    echo "$number is negative.<br>";
} else {
    echo "$number is zero.<br>";
}

// Check if the number is odd or even
if ($number % 2 == 0) {
    echo "$number is an even number.<br>";
} else {
    echo "$number is an odd number.<br>";
}

// Check if the number is a multiple of 5
if ($number % 5 == 0) {
    echo "$number is a multiple of 5.<br>";
} else {
    echo "$number is not a multiple of 5.<br>";
}
?>

With $number = 10, the output is:

10 is positive.
10 is an even number.
10 is a multiple of 5.

Each if block runs independently โ€” PHP does not short-circuit the second or third check just because the first one matched.

Chapter 4: Combining Conditions โ€” Full Script

The class combined all three checks into a single, clean script. This is the canonical "number analyser" pattern โ€” a complete working program:

<?php
// Define the number
$number = 10;

// Check if the number is positive, negative, or zero
if ($number > 0) {
    echo "$number is positive.<br>";
} else if ($number < 0) {
    echo "$number is negative.<br>";
} else {
    echo "$number is zero.<br>";
}

// Check if the number is odd or even
if ($number % 2 == 0) {
    echo "$number is an even number.<br>";
} else {
    echo "$number is an odd number.<br>";
}

// Check if the number is a multiple of 5
if ($number % 5 == 0) {
    echo "$number is a multiple of 5.<br>";
} else {
    echo "$number is not a multiple of 5.<br>";
}
?>

Try changing $number to 7, -4, or 0 and trace the output mentally before running it โ€” that trace practice is how the class internalises conditional logic.

Chapter 5: Dynamic Input โ€” Interactive Script

Hard-coded variables are useful for learning, but real programs respond to user input. The class upgraded the script to accept a number from an HTML form submitted via POST.

The key PHP superglobal here is $_SERVER["REQUEST_METHOD"] โ€” it tells the script whether the page was opened fresh (GET) or whether a form was submitted (POST). The submitted value arrives in $_POST['number'].

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Number Checker</title>
</head>
<body>

    <h1>Enter a Number</h1>
    <form method="post">
        <input type="number" name="number" required>
        <button type="submit">Check</button>
    </form>

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the number from the form
        $number = $_POST['number'];

        // Check if the number is positive, negative, or zero
        if ($number > 0) {
            echo "$number is positive.<br>";
        } else if ($number < 0) {
            echo "$number is negative.<br>";
        } else {
            echo "$number is zero.<br>";
        }

        // Check if the number is odd or even
        if ($number % 2 == 0) {
            echo "$number is an even number.<br>";
        } else {
            echo "$number is an odd number.<br>";
        }

        // Check if the number is a multiple of 5
        if ($number % 5 == 0) {
            echo "$number is a multiple of 5.<br>";
        } else {
            echo "$number is not a multiple of 5.<br>";
        }
    }
    ?>

</body>
</html>

How the flow works:

flowchart TD
    A[Browser opens page] --> B{REQUEST_METHOD == POST?}
    B -- No --> C[Show form only]
    B -- Yes --> D[Read $_POST['number']]
    D --> E{number > 0?}
    E -- Yes --> F[echo: positive]
    E -- No --> G{number < 0?}
    G -- Yes --> H[echo: negative]
    G -- No --> I[echo: zero]
    F & H & I --> J{number % 2 == 0?}
    J -- Yes --> K[echo: even]
    J -- No --> L[echo: odd]
    K & L --> M{number % 5 == 0?}
    M -- Yes --> N[echo: multiple of 5]
    M -- No --> O[echo: not a multiple of 5]

Key points about the interactive version:

  • method="post" on the <form> tag tells the browser to send data as a POST request.
  • name="number" on the <input> is the key used to retrieve the value with $_POST['number'].
  • The required attribute on the input prevents the form from submitting an empty value.
  • Wrapping the PHP logic inside if ($_SERVER["REQUEST_METHOD"] == "POST") means the analysis section only runs after a form submission, not on the initial page load.
  • The form and the PHP output live in the same file โ€” the form submits back to itself (no action attribute defaults to the current URL).

๐Ÿงช Try It Yourself

Task: Build a grade classifier.

Create a file called grade.php. Add an HTML form with a number input (0โ€“100) named score. On form submission, use if / else if / else to echo one of the following messages:

  • Score โ‰ฅ 90 โ†’ "Grade: A"
  • Score โ‰ฅ 80 โ†’ "Grade: B"
  • Score โ‰ฅ 70 โ†’ "Grade: C"
  • Score โ‰ฅ 60 โ†’ "Grade: D"
  • Score < 60 โ†’ "Grade: F"

Success criterion: Type 85 in the field, click Submit, and see Grade: B appear below the form on the same page.

Starter snippet:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Grade Classifier</title>
</head>
<body>
    <h1>Grade Classifier</h1>
    <form method="post">
        <input type="number" name="score" min="0" max="100" required>
        <button type="submit">Classify</button>
    </form>

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $score = $_POST['score'];
        // TODO: add your if / else if / else chain here
        echo "Score: $score<br>";
    }
    ?>
</body>
</html>

๐Ÿ” Checkpoint Quiz

Q1. What is the difference between using a single if / else if / else chain versus three separate if statements for three independent checks?

A) There is no difference โ€” they behave identically. B) A single chain stops after the first matching condition; three separate if statements all run independently. C) Three separate if statements are slower because PHP evaluates them all. D) else if can only be used once per script.


Q2. Given the following snippet, what is printed?

<?php
$number = 9;

if ($number % 2 == 0) {
    echo "even";
} else {
    echo "odd";
}

if ($number % 5 == 0) {
    echo " and multiple of 5";
} else {
    echo " and not multiple of 5";
}
?>

A) even and multiple of 5 B) odd and multiple of 5 C) odd and not multiple of 5 D) even and not multiple of 5


Q3. A classmate writes the following PHP and complains it always prints "zero" even when they submit 5. What is the bug?

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $number = $_POST["num"];
    if ($number = 0) {
        echo "zero";
    } else {
        echo "not zero";
    }
}
?>

A) $_POST["num"] should be $_GET["num"] B) $number = 0 is an assignment, not a comparison โ€” it should be $number == 0 C) The else branch is missing a condition D) echo cannot be inside an if block


Q4. You are building a ticket-price calculator. Adults (age โ‰ฅ 18) pay $12; seniors (age โ‰ฅ 65) pay $8; children (age < 18) pay $5. Which ordering of conditions is correct?

A) Check age >= 18 first, then age >= 65, then age < 18 B) Check age >= 65 first, then age >= 18, then the else for children C) Check age < 18 first, then the else for adults D) Order does not matter when using else if

A1. B โ€” A single if / else if / else chain is mutually exclusive: once one branch matches, the rest are skipped. Three separate if statements each evaluate independently, so multiple results can print.

A2. C โ€” 9 % 2 is 1 (not 0), so "odd" prints. 9 % 5 is 4 (not 0), so "not multiple of 5" prints. Final output: odd and not multiple of 5.

A3. B โ€” $number = 0 uses a single =, which is the assignment operator. It assigns 0 to $number and evaluates to 0 (falsy)... wait, actually 0 is falsy so the if body never runs โ€” but the real bug is still the single = instead of ==. The assignment replaces the value and creates unpredictable behaviour; the fix is $number == 0.

A4. B โ€” The senior condition (age >= 65) must come before the adult condition (age >= 18), because a 70-year-old satisfies both. If age >= 18 is checked first, seniors would be caught there and never reach the $8 branch. Always check the more specific (narrower) condition first.

๐Ÿชž Recap

  • echo outputs strings and interpolated variables to the browser; use double quotes to embed $variables directly.
  • if / else if / else forms a mutually exclusive decision chain โ€” only one branch executes per chain.
  • Multiple independent if statements run in sequence regardless of each other's results โ€” use them when questions are unrelated.
  • The % (modulo) operator returns the division remainder and is the standard tool for odd/even and divisibility checks.
  • Combine an HTML form (method="post") with $_SERVER["REQUEST_METHOD"] and $_POST to drive PHP logic from real user input.

๐Ÿ“š Further Reading

Like this topic? Itโ€™s one of 48 in Full Stack Essentials.

Block your seat for โ‚น2,500 and join the next cohort.