Logical operators
Learn boolean logic and short-circuit evaluation with &&, || and !.
Logical operators
To combine several conditions you use logical operators. && (AND) returns true when both sides are true. || (OR) returns true when at least one side is true. ! (NOT) flips the value.
For example, to pass through a door you need to be over 18 AND have an ID: $age >= 18 && $hasId. If both conditions are not met, you cannot pass.
Short-circuit evaluation
The && and || operators short-circuit: they evaluate left to right and stop once the result is certain. In $hasId && $hasTicket, if $hasId is false, the right side is never evaluated because the result is already false.
This prevents unnecessary checks. With $inStock && $count > 0, if the item is not in stock, the $count > 0 check is never reached; you get the same result faster.
Exercise Access control
Write an if with the condition $age >= 18 && $hasId. When true, print "allowed" with echo; otherwise print "denied". You must use an else branch.
Show example solution
To combine conditions, write if ($age >= 18 && $hasId) { ... } else { ... }.
Example solution:
<?php
$age = 20;
$hasId = true;
// Access control
if ($age >= 18 && $hasId) {
echo "allowed";
} else {
echo "denied";
}
Test yourself
-
$age = 20; $hasId = true; var_dump($age >= 18 && $hasId); output?
$age = 20; $hasId = true; var_dump($age >= 18 && $hasId);- bool(false)
- bool(true)
- int(1)
- NULL
Show answer
bool(true) — Correct. 20 >= 18 is true and $hasId is true; both true, result is true.
-
Write the logical AND operator
$age = 20; $hasId = true; var_dump($age >= 18 ____ $hasId);Show answer
$age = 20; $hasId = true; var_dump($age >= 18 && $hasId); -
Match each operator to its meaning
- &&
- Logical AND
- ||
- Logical OR
- !
- NOT