Logical operators combine several conditions into one answer.
| Operator | Meaning | True when… |
|---|---|---|
&& | AND | both sides are true |
|| | OR | at least one side is true |
! | NOT | the value is false (it flips the result) |
xor | Exclusive OR | exactly one side is true |
<?php
$age = 25;
$hasTicket = true;
var_dump($age >= 18 && $hasTicket);
var_dump($age < 18 || $hasTicket);
var_dump(!$hasTicket);
bool(true)
bool(true)
bool(false)
Short-circuit evaluation
PHP stops as soon as it knows the answer. With &&, if the left side is false, the right side is never run. With ||, if the left side is true, the right side is skipped.
<?php
function check(string $label): bool
{
echo "checking $label\n";
return true;
}
false && check("A");
true || check("B");
true && check("C");
checking C
Only C ran. This is useful: you can guard a risky check with a safe one.
<?php
$user = null;
if ($user !== null && $user["active"]) {
echo "Active user";
} else {
echo "No active user";
}
No active user
If PHP evaluated the second half with $user set to null, it would complain. The first half protects it.
&& vs and
PHP also has the words and and or. They do the same job, but they bind more loosely than =, which gives a trap.
<?php
$result = true and false; // read as: ($result = true) and false
var_dump($result);
$result = (true and false);
var_dump($result);
bool(true)
bool(false)
In the first line, PHP assigns true first, and only then applies and. So $result is true.
Use && and
and and or have the lowest precedence, so they can behave unexpectedly. Stick to && and ||.Exercise: can they ride?
A ride needs height of at least 120 cm and an adult with them, or an age of 14 or more. Write the condition for $height, $hasAdult and $age.
Show a possible solution
<?php
$height = 130;
$hasAdult = false;
$age = 15;
$canRide = ($height >= 120 && $hasAdult) || $age >= 14;
var_dump($canRide);
bool(true)