PHP If...Else
What Is if...else ? In simple terms: if...else chooses between two actions: one when a condition is true, and another when it is false. Technically: The else clause attaches to an if statement and pro
What Is if...else?
In simple terms: if...else chooses between two actions: one when a condition is true, and another when it is false.
Technically: The else clause attaches to an if statement and provides a block that runs when the if condition evaluates to false. Exactly one of the two blocks always runs.
Why It Is Needed
A plain if only describes what happens when a condition is true. Many decisions have two meaningful outcomes:
- Logged in → show the dashboard; otherwise → show the login form.
- Payment succeeded → confirm the order; otherwise → show an error.
- Stock available → enable "Add to cart"; otherwise → show "Notify me".
if...else expresses both outcomes in one structure, so the reader sees the full decision in one place.
Syntax
if (condition) {
// runs when condition is true
} else {
// runs when condition is false
}
Example: Even or Odd
<?php
$number = 7;
if ($number % 2 === 0) {
echo "$number is even\n";
} else {
echo "$number is odd\n";
}
Output
7 is odd
How It Works
$number % 2is the remainder after dividing by 2, which is1for 7.1 === 0isfalse, so theifblock is skipped.- The
elseblock runs. - Execution continues after the closing
}of theelseblock.
condition?
/ \
true false
| |
[if block] [else block]
\ /
code after if...else
Practical Example: Checking a Password
<?php
$storedHash = password_hash('Secure#2026', PASSWORD_DEFAULT);
$attempts = ['secure#2026', 'Secure#2026'];
foreach ($attempts as $input) {
if (password_verify($input, $storedHash)) {
echo "'$input': login successful\n";
} else {
echo "'$input': incorrect password\n";
}
}
Output
'secure#2026': incorrect password
'Secure#2026': login successful
How It Works
password_hash()creates a secure, salted hash of the password. Applications store only this hash, never the plain password.password_verify()checks whether an input matches the hash and returnstrueorfalse, which makes it a perfectifcondition.- Passwords are case-sensitive, so the first attempt fails.
Password handling is covered in Password Hashing. (In a real login form, never echo the entered password back to the page.)
Assigning Values in Each Branch
A common use of if...else is to give a variable one of two values.
Example
<?php
$cartTotal = 750;
if ($cartTotal >= 999) {
$shippingFee = 0;
} else {
$shippingFee = 79;
}
echo "Shipping: ₹$shippingFee\n";
Output
Shipping: ₹79
Both branches assign $shippingFee, so the variable is guaranteed to exist after the statement.
Alternative: Default Value, Then Override
<?php
$cartTotal = 750;
$shippingFee = 79;
if ($cartTotal >= 999) {
$shippingFee = 0;
}
echo "Shipping: ₹$shippingFee\n";
This version sets the common case first and changes it only when the condition is true. Both styles are valid; the default-first style is convenient when the else branch would only assign a value.
Alternative: Ternary Operator
When each branch only produces a value, the ternary operator expresses the same decision in one line:
$shippingFee = $cartTotal >= 999 ? 0 : 79;
The ternary operator is covered in PHP Shorthand if. Use if...else when branches contain several statements or when a one-line expression would become hard to read.
if...else Inside Functions
When both branches return, the else keyword is not strictly needed, because return already ends the function:
<?php
function stockLabel(int $quantity): string
{
if ($quantity > 0) {
return "In stock ($quantity available)";
}
return "Out of stock";
}
echo stockLabel(12) . "\n";
echo stockLabel(0) . "\n";
Output
In stock (12 available)
Out of stock
If $quantity > 0, the function returns immediately; otherwise execution reaches the final return. Leaving out the redundant else reduces nesting, which matters as functions grow. Both forms are correct — choose the one that reads most clearly.
Multiple Statements in Each Branch
Each branch can contain any amount of code:
<?php
$order = ['id' => 9021, 'paid' => false, 'total' => 1450];
$log = [];
if ($order['paid']) {
$status = 'confirmed';
$log[] = "Order {$order['id']} confirmed";
$message = "Thank you! Your order is confirmed.";
} else {
$status = 'awaiting_payment';
$log[] = "Order {$order['id']} waiting for payment of ₹{$order['total']}";
$message = "Please complete the payment to confirm your order.";
}
echo "Status: $status\n";
echo "Message: $message\n";
echo "Log: " . implode('; ', $log) . "\n";
Output
Status: awaiting_payment
Message: Please complete the payment to confirm your order.
Log: Order 9021 waiting for payment of ₹1450
Every variable is set in both branches, so code after the statement can use them safely. If a variable is set in only one branch, it will be undefined in the other case.
if...else in HTML Templates
In templates, the alternative syntax (if:, else:, endif;) keeps the HTML readable:
<?php $user = ['name' => 'Nila', 'unread' => 0]; ?>
<?php if ($user['unread'] > 0): ?>
<p>You have <?= $user['unread'] ?> unread messages.</p>
<?php else: ?>
<p>No new messages, <?= htmlspecialchars($user['name']) ?>.</p>
<?php endif; ?>
Output (HTML)
<p>No new messages, Nila.</p>
See Alternative Syntax for details.
Common Mistakes
Variable Defined in Only One Branch
<?php
$score = 30;
if ($score >= 40) {
$result = 'Pass';
}
echo $result;
Output
PHP Warning: Undefined variable $result in /path/script.php on line 8
Fix: Assign the variable in an else branch, or initialize it before the if.
The Dangling else
When braces are omitted, an else belongs to the nearest preceding if, regardless of indentation:
<?php
$isMember = false;
$cartTotal = 1500;
if ($isMember)
if ($cartTotal > 1000)
echo "Free gift added\n";
else
echo "Join our membership to get free gifts\n";
echo "Done\n";
Output
Done
The indentation suggests that the else belongs to if ($isMember), but PHP attaches it to the inner if ($cartTotal > 1000). Because $isMember is false, the entire inner statement — including its else — is skipped, so the membership message never appears.
Fix: Always use braces:
<?php
$isMember = false;
$cartTotal = 1500;
if ($isMember) {
if ($cartTotal > 1000) {
echo "Free gift added\n";
}
} else {
echo "Join our membership to get free gifts\n";
}
Output
Join our membership to get free gifts
Negative Conditions With else
if (!$isActive) {
echo "Account inactive";
} else {
echo "Account active";
}
This forces the reader to resolve "not not active" for the else branch. Prefer the positive condition first:
if ($isActive) {
echo "Account active";
} else {
echo "Account inactive";
}
Using if...else for Independent Checks
Effect: Only one branch runs, even when both conditions could be relevant.
Fix: Use separate if statements for independent checks.
Best Practices
- Always use braces for both the
ifand theelseblock. - Make sure variables used after the statement are set in every branch (or before the statement).
- Put the positive or most common case first when it improves readability.
- Use the ternary operator for simple value choices and
if...elsefor multiple statements. - Inside functions, consider returning early instead of using
elseto reduce nesting.
Official reference: https://www.php.net/manual/en/control-structures.else.php