PHP Nested If
A nested if places one conditional statement inside another so you can test a second condition only after the first one has already passed.
What nesting means
Sometimes a decision depends on more than one thing, and the second question only makes sense once the first has been answered. Nesting an if statement inside another lets you express that layered logic: the inner condition is checked only when the outer condition is true. If the outer test fails, PHP never even looks at the inner one, which can save unnecessary work and mirrors how we reason in everyday life.
A nested if statement
<?php
$age = 25;
$hasLicense = true;
if ($age >= 18) {
// Only reached when the person is an adult
if ($hasLicense) {
echo "You are allowed to drive.";
} else {
echo "You are old enough but need a license first.";
}
} else {
echo "You are too young to drive.";
}
?>Nesting versus combined conditions
Not every layered test needs nesting. When you simply require two conditions to both be true and there is no separate message for the in-between case, joining them with the logical AND operator is cleaner. Reach for a nested if when each level needs its own distinct handling, such as a different message when the outer test passes but the inner one fails.
- Use && to combine conditions when you only care about the all-true case.
- Use nesting when the outer and inner failures need different responses.
- Avoid nesting more than two or three levels deep, as it quickly becomes hard to follow.
- Consider returning early or using elseif to keep deeply nested logic flat and readable.
The same logic without nesting
<?php
$age = 25;
$hasLicense = true;
if ($age >= 18 && $hasLicense) {
echo "You are allowed to drive.";
} else {
echo "You cannot drive yet.";
}
// Shorter, but it loses the separate "needs a license" message
?>A practical multi-level example
The example below decides a shipping message. First it confirms the order exists, then whether it is paid, and finally whether the address is complete. Each layer builds on the previous one, and each failure gives the customer a specific, helpful reason.
Layered validation
<?php
$orderTotal = 1500;
$isPaid = true;
$address = "12 Park Street, Chennai";
if ($orderTotal > 0) {
if ($isPaid) {
if ($address !== "") {
echo "Order confirmed and ready to ship.";
} else {
echo "Payment received, but we need a delivery address.";
}
} else {
echo "Your order is waiting for payment.";
}
} else {
echo "Your cart is empty.";
}
?>