Logical Operators
Logical Operators What Are Logical Operators? In simple terms: Logical operators combine or reverse conditions. They let you say "this and that", "this or that", or "not this". Technically: Logical op
Logical Operators What Are Logical Operators? In simple terms: Logical operators combine or reverse conditions. They let you say "this and that", "this or that", or "not this". Technically: Logical operators work on boolean values. Each operand is converted to bool (using PHP's truthiness rules), and the operator returns true or false. Operator Name true When $a && $b And Both $a and $b are true $a and $b And (low precedence) Both are true $a || $b Or At least one is true $a or $b Or (low precedence) At least one is true !$a Not $a is false $a xor $b Exclusive or Exactly one of them is true
Why They Matter Real decisions rarely depend on a single condition. Whether a user can edit a post depends on their role and ownership; whether shipping is free depends on the cart total or a membership; whether to show a warning depends on something not being set. Logical operators express these rules.
AND: && && returns true only when both operands are true. $a $b $a && $b true true true true false false false true false false false false
Example <?php $age = 22; $hasLicense = true;
if ($age >= 18 && $hasLicense) { echo "You can rent a car.\n"; }
$score = 105; $isValidScore = $score >= 0 && $score <= 100; var_dump($isValidScore);
Output You can rent a car. bool(false)
A range check is the most common use of &&: the score must be at least 0 and at most 100. 105 fails the second condition.
OR: || || returns true when at least one operand is true. $a $b $a || $b true true true true false true false true true false false false
Example <?php $cartTotal = 650; $isPrimeMember = true;
$freeShipping = $cartTotal >= 999 || $isPrimeMember;
var_dump($freeShipping);
Output bool(true)
The cart total is too low, but the customer is a member, so one true condition is enough.
NOT: ! ! reverses a boolean: !true is false, and !false is true. Example <?php $isLoggedIn = false; $errors = [];
if (!$isLoggedIn) { echo "Please log in.\n"; }
if (!$errors) { echo "No errors.\n"; }
Output Please log in. No errors.
!$errors converts the array to a boolean first: an empty array is falsy, so !$errors is true. For clarity, many developers prefer the explicit form $errors === []. Precedence Trap With ! ! has higher precedence than comparison operators, so it applies only to the value directly after it: <?php $balance = -3;
var_dump(!$balance > 0); // (!$balance) > 0 var_dump(!($balance > 0)); // intended: "balance is not positive"
Output bool(false) bool(true)
In the first line, !$balance turns -3 into false, and false > 0 is false. Wrap the condition in parentheses when negating a comparison — or, better, write the opposite comparison directly: $balance <= 0.
XOR: xor xor (exclusive or) returns true when exactly one operand is true. $a $b $a xor $b true true false true false true false true true false false false
Example <?php $email = 'meera@example.com'; $phone = '98765 43210';
$exactlyOneContact = (($email !== '') xor ($phone !== ''));
var_dump($exactlyOneContact);
Output bool(false)
This checks that the user provided an email or a phone number, but not both. Both are filled in here, so the result is false. xor has lower precedence than =, so the outer parentheses are essential. Without them, $exactlyOneContact = ($email !== '') xor ($phone !== '') would assign only the first comparison (true) and discard the rest. An equivalent, often clearer form is ($email !== '') !== ($phone !== '').
Logical Operators Always Return Booleans In some languages (such as JavaScript), || returns one of its operands. PHP's logical operators always return true or false: <?php var_dump("hello" && 5); var_dump(0 || ""); var_dump("PHP" || "default");
Output bool(true) bool(false) bool(true)
"hello" and 5 are both truthy, so && returns true. 0 and "" are both falsy, so || returns false. The third result is true — not the string "PHP". Because $name || 'Guest' returns a boolean, it cannot be used to provide a default value as in JavaScript. Use the null coalescing operator ($name ?? 'Guest') or the short ternary ($name ?: 'Guest') instead.
Short-Circuit Evaluation PHP stops evaluating a logical expression as soon as the result is known: && stops at the first false operand (the result can only be false). || stops at the first true operand (the result can only be true). Example <?php function check(string $label, bool $result): bool { echo "Checking $label\n"; return $result; }
echo "--- AND ---\n"; var_dump(check('A', false) && check('B', true));
echo "--- OR ---\n"; var_dump(check('C', true) || check('D', false));
Output --- AND --- Checking A bool(false) --- OR --- Checking C bool(true)
check('B', ...) and check('D', ...) never run, because the first operand already decided the result. Why Short-Circuiting Matters
- Guarding against errors. Put the safety check first: <?php $user = ['name' => 'Ravi'];
if (isset($user['age']) && $user['age'] >= 18) { echo "Adult\n"; } else { echo "Age unknown or under 18\n"; }
Output Age unknown or under 18
If age is missing, isset() returns false and the second condition — which would raise an "Undefined array key" warning — is never evaluated.
Performance. Put cheap checks before expensive ones (such as database queries or API calls), so the expensive check runs only when needed: if ($user->isActive() && $permissionService->canExport($user)) { ... }
Side effects. Because some operands may not run, never place code that must execute (such as logging or saving) inside the right side of && or ||.
&& / || vs and / or and and or behave like && and ||, but with much lower precedence — lower even than the assignment operator =. Example <?php $a = true && false; $b = true and false;
$c = false || true; $d = false or true;
var_dump($a, $b, $c, $d);
Output bool(false) bool(true) bool(true) bool(false)
Why $b and $d Are Surprising $b = true and false is evaluated as ($b = true) and false. The assignment happens first, so $b is true; the and false part is evaluated and discarded. $d = false or true is evaluated as ($d = false) or true, so $d is false. The Legacy or die() Pattern You may see this in older code: $connection = mysqli_connect($host, $user, $pass) or die('Connection failed');
Because or has lower precedence than =, the connection result is assigned first, and die() runs only if that result is falsy. The pattern works, but it is outdated: it prints a raw message to the user and stops the script without proper error handling. Modern code uses exceptions (for example, mysqli and PDO can throw exceptions on connection failure) and handles errors centrally. Recommendation: use &&, ||, and ! in all conditions and assignments. Avoid and, or, and xor unless you specifically need their low precedence, and add parentheses when you do.
Combining && and || && has higher precedence than ||, similar to how multiplication binds tighter than addition: <?php var_dump(true || false && false); var_dump((true || false) && false);
Output bool(true) bool(false)
The first line is evaluated as true || (false && false). Whenever a condition mixes && and ||, add parentheses so readers do not need to remember precedence rules. De Morgan's Laws Negating a combined condition flips each part and swaps && with ||: Expression Equivalent !($a && $b) !$a || !$b !($a || $b) !$a && !$b
This helps simplify conditions: <?php $isWeekend = false; $isHoliday = false;
// "Not (weekend or holiday)" is the same as "not weekend and not holiday" var_dump(!($isWeekend || $isHoliday)); var_dump(!$isWeekend && !$isHoliday);
Output bool(true) bool(true)
Practical Example: Edit Permissions <?php function canEditPost(array $user, array $post): bool { $isAdmin = $user['role'] === 'admin'; $isAuthor = $user['id'] === $post['author_id']; $isEditable = !$post['locked'] && $post['status'] !== 'archived';
return $isAdmin || ($isAuthor && $isEditable); }
$post = ['author_id' => 7, 'locked' => false, 'status' => 'published']; $lockedPost = ['author_id' => 7, 'locked' => true, 'status' => 'published'];
$author = ['id' => 7, 'role' => 'writer']; $otherWriter = ['id' => 9, 'role' => 'writer']; $admin = ['id' => 1, 'role' => 'admin'];
var_dump(canEditPost($author, $post)); var_dump(canEditPost($author, $lockedPost)); var_dump(canEditPost($otherWriter, $post)); var_dump(canEditPost($admin, $lockedPost));
Output bool(true) bool(false) bool(false) bool(true)
Step-by-Step Explanation Each part of the rule is stored in a named boolean ($isAdmin, $isAuthor, $isEditable). The final expression reads almost like the business rule: "an admin, or the author of an editable post". $isEditable combines ! and &&: the post is not locked and not archived. The parentheses around $isAuthor && $isEditable make the grouping explicit, even though && already binds tighter than ||. In this version, all three booleans are calculated before the return, so every check runs. If one of the checks were expensive (for example, a database query), writing it directly inside the return expression would let short-circuiting skip it when $isAdmin is already true. The results: the author can edit their unlocked post; the author cannot edit a locked post; another writer cannot edit it; an admin can edit anything.
Common Mistakes Using and / or in Assignments Effect: Only the first operand is assigned. Fix: Use && and ||. Expecting || to Return a Value Effect: $name = $input || 'Guest'; stores true or false. Fix: $name = $input ?? 'Guest'; or $input ?: 'Guest'. Negating Without Parentheses Effect: !$count > 0 negates $count, not the comparison. Fix: !($count > 0) or $count <= 0. Mixing && and || Without Parentheses Effect: Conditions are grouped differently than intended. Fix: Always parenthesize mixed conditions. Putting the Guard After the Risky Check Effect: $user['age'] >= 18 && isset($user['age']) still triggers a warning when the key is missing. Fix: Put isset() or !== null checks first. Using & or | Instead of && or || Effect: & and | are bitwise operators. They do not short-circuit and they operate on integers, which can produce surprising results. Fix: Use the double forms for conditions.
Best Practices Use &&, ||, and ! for conditions; avoid and, or, and xor unless you understand their precedence and add parentheses. Put cheap and protective checks first to benefit from short-circuiting. Store parts of complex rules in well-named boolean variables. Parenthesize every condition that mixes && and || or negates a comparison. Use ?? or ?: for default values; logical operators return only booleans. Official reference: https://www.php.net/manual/en/language.operators.logical.php