if, else & elseif
Programs are useful because they make decisions. Free delivery or not? Pass or fail? Show the login link or the user's name? In PHP, you make these decisions with if, else and elseif.
In this lesson you will learn how to run code only when a condition is true, how to choose between several options, and how to write decisions neatly inside HTML pages.
The if statement
An if statement runs a block of code only when its condition is true. The condition goes in round brackets, and the code to run goes in curly braces:
<?php
declare(strict_types=1);
$cartTotal = 620;
$deliveryFee = 40;
if ($cartTotal >= 499) {
$deliveryFee = 0;
echo "You get free delivery!\n";
}
echo "Delivery fee: ₹$deliveryFee\n";You get free delivery! Delivery fee: ₹0
Change $cartTotal to 300 and run it again. The block is skipped, so only the last line prints, with a fee of ₹40.
The condition can be any expression. PHP converts it to a boolean using the truthy and falsy rules from Data Types. Most of the time, you will write a comparison with operators such as >=, === or !==, as shown in Operators.
Always use curly braces, even for a single line. PHP allows you to leave them out for one statement, but then adding a second line later silently breaks the logic.
else and elseif
else runs when the if condition is false. elseif lets you test another condition when the previous ones were false. PHP checks the conditions from top to bottom and runs only the first block whose condition is true:
<?php
declare(strict_types=1);
$marks = 78;
if ($marks >= 90) {
$grade = 'A+';
} elseif ($marks >= 75) {
$grade = 'A';
} elseif ($marks >= 60) {
$grade = 'B';
} elseif ($marks >= 33) {
$grade = 'C';
} else {
$grade = 'Fail';
}
echo "Marks: $marks, Grade: $grade\n";Marks: 78, Grade: A
78 is also greater than 60 and 33, but PHP stops at the first match, >= 75. That is why the order matters: check the strictest condition first. If you put >= 33 at the top, every passing student would get a C.
You can also write else if as two words, and it works the same with curly braces. Most PHP code uses elseif, and only elseif works in the template syntax shown later in this lesson.
When the only job of an if is to choose between two values, the ternary operator from Operators is shorter: $result = $marks >= 33 ? 'Pass' : 'Fail';. For more than two values, the match expression in the next lesson is often clearer than a long elseif chain.
Combining conditions
Use && (and), || (or) and ! (not) to combine conditions. Each branch can test something different:
<?php
declare(strict_types=1);
$age = 21;
$isStudent = true;
$hasIdCard = false;
if ($age >= 60) {
echo "Senior citizen concession\n";
} elseif ($isStudent && $hasIdCard) {
echo "Student concession\n";
} elseif ($isStudent) {
echo "Please show your student ID card\n";
} else {
echo "Full fare\n";
}Please show your student ID card
You could also put one if inside another, which is called nesting. Nesting is fine for one level, but deeply nested code is hard to read. Combining conditions with &&, as above, usually keeps the code flat.
Watch out for truthiness
Writing if ($value) is short, but it treats 0, '0' and '' all as false. With form data, that can reject real answers:
<?php
declare(strict_types=1);
$score = '0';
if ($score) {
echo "Score entered\n";
} else {
echo "No score entered\n";
}
if ($score !== '') {
echo "Score entered: $score\n";
}No score entered Score entered: 0
The first check gets it wrong: the student scored zero, which is a real score. The second check says exactly what it means: "is the string not empty?". Prefer explicit checks such as !== '', !== null or count($list) > 0, so your code does what you mean, not what PHP guesses.
if inside HTML templates
When you mix PHP with HTML, curly braces spread over many <?php ?> tags are hard to follow. PHP has an alternative syntax for templates: a colon : replaces the opening brace, and endif; closes the block.
<?php
declare(strict_types=1);
$user = 'Meera';
$unreadMessages = 3;
?>
<?php if ($user !== null): ?>
<p>Welcome back, <?= htmlspecialchars($user) ?>!</p>
<?php if ($unreadMessages > 0): ?>
<p>You have <?= $unreadMessages ?> new messages.</p>
<?php endif; ?>
<?php else: ?>
<p><a href="/login">Log in</a></p>
<?php endif; ?><p>Welcome back, Meera!</p> <p>You have 3 new messages.</p>
The browser shows the welcome line and the message count. If you set $user = null, it shows only the "Log in" link. The function htmlspecialchars() makes text safe to put inside HTML; you will learn why it matters in Form Validation & Escaping.
Common mistakes
- Using
=instead of===.if ($status = 'paid')assigns the value and is always true. Use===to compare. - Wrong order in an
elseifchain. Put the strictest or most specific condition first. - A semicolon after the condition.
if ($x > 5);ends theifimmediately, so the block after it always runs. - Relying on truthiness for user input.
'0'is falsy. Compare explicitly. - Leaving out the braces. A second line added later will run every time.
Key points
ifruns a block only when its condition is true;elseruns when it is false.elseiftests further conditions; only the first true branch runs, so order matters.- Combine conditions with
&&,||and!to keep code flat. - Use explicit comparisons like
!== ''instead of relying on truthy and falsy values. - In HTML templates, use the alternative syntax
if (...):,elseif (...):,else:andendif;.
Exercise
An electricity board charges by units used: up to 100 units cost ₹3 per unit, 101 to 300 units cost ₹5 per unit, and above 300 units cost ₹7 per unit (the whole bill uses one rate, to keep it simple). Write a script with $units = 240 that picks the rate with if, elseif and else, then prints the units, rate and total bill. Add a final check that prints "High usage alert" when the units are above 300.
Show solution
<?php
declare(strict_types=1);
$units = 240;
if ($units <= 100) {
$rate = 3;
} elseif ($units <= 300) {
$rate = 5;
} else {
$rate = 7;
}
$bill = $units * $rate;
echo "Units: $units, Rate: ₹$rate, Bill: ₹$bill\n";
if ($units > 300) {
echo "High usage alert\n";
}Units: 240, Rate: ₹5, Bill: ₹1200
Because the first condition is <= 100, the second branch only needs to check <= 300; any value reaching it is already above 100. The alert stays silent for 240 units.
Quick Quiz
1. What does PHP do in an if/elseif chain when two conditions are true?
PHP checks conditions in order and stops at the first one that is true.
2. What is wrong with if ($role = 'admin')?
A single = assigns; use === to compare.
3. Which keyword closes an if block in the alternative template syntax?
The alternative syntax uses if (...): and closes with endif;.
4. $qty = '0'; Which condition correctly checks that a quantity was entered?
'0' is falsy, so only an explicit comparison with the empty string gives the right answer.
Learn PHP with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
