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, andelseblocks to branch program logic - Chain multiple independent
ifchecks in a single script - Accept user input via an HTML form and drive
iflogic 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 istrue.else if(also writtenelseif) โ tests a new condition when the precedingifwasfalse.elseโ executes a fallback block when all preceding conditions werefalse.
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:
- PHP evaluates
$number > 0. Because10 > 0istrue, it enters the first block and echoes10 is positive.. - The
else ifandelsebranches are skipped entirely. - If
$numberwere-3, the first condition would befalse, theelse if ($number < 0)would betrue, and the second message would print. - If
$numberwere0, bothifandelse ifwould befalse, so theelseblock 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
requiredattribute 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
actionattribute 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
echooutputs strings and interpolated variables to the browser; use double quotes to embed$variablesdirectly.if/else if/elseforms a mutually exclusive decision chain โ only one branch executes per chain.- Multiple independent
ifstatements 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$_POSTto drive PHP logic from real user input.
๐ Further Reading
- PHP
ifstatement โ Official Docs โ the source of truth on conditional syntax and edge cases - PHP
echoโ Official Docs โ covers multi-string syntax and performance notes vsprint - PHP
$_POSTsuperglobal โ Official Docs โ how form data arrives in PHP - โฌ ๏ธ Previous: PHP Variables (introduction)
- โก๏ธ Next: Element Design (Based on the picture/requirement)