Logical Operators and Short-Circuiting

3.Logical Operators and Short-Circuiting

M

In this chapter

We'll learn how to join true/false questions with && (and), || (or) and ! (not), why && is worked out before || — the cause of the double booking — how short-circuiting lets PHP skip work and avoid errors, and the trap hidden in the words and and or.

14–16 min

The Problem in Real Life

Marcus writes the booking rule on the whiteboard, the way Olivia explained it: "A slot can be booked if it's free — and the customer is a member or pays online." Then he writes Mia's line underneath: $isFree && $isMember || $paysOnline.

"Read it out loud," he says. She does: "free, and member, or pays online." It sounds the same as the rule. Then he fills in Friday's values for Alex: the slot was not free, Alex was not a member, but Alex did pay online. false && false || true. PHP says: true.

"The words are the same," says Marcus. "The grouping isn't. PHP grouped your line differently from Olivia's sentence."

M

The slot wasn't free. How can the whole check still be true?

Mia

The Rule as Spoken vs. the Rule as PHP Reads It

One slot, two customers

An online payer could book a slot that was already taken.

Hidden grouping

&& is worked out before ||, so the line didn't mean what it said.

Skipped checks

PHP stops evaluating as soon as the answer is known — useful, if you know it happens.

Logical Operators and Short-Circuiting

Logical operators: a logical operator combines true/false values (bools — Act 04) into one answer. They're how code says "this and that", "this or that" and "not this". PHP's main three:

  • And, written &&: true only if both sides are true.
  • Or, written ||: true if at least one side is true.
  • Not, written !: flips one value — !true is false.

How they combine: the table below is called a truth table — it lists every combination of two bools and the result of each operator. Read it once and the operators hold no surprises. && is the strict one: both must be true. || is the generous one: either is enough. ! goes in front of a single value: !$isFree means "not free". If a side isn't a bool, PHP converts it first, using the rules from Act 04 (0, "", "0", null, [] are false).

Table — Truth table
$a$b$a && $b$a || $b!$a
truetruetruetruefalse
truefalsefalsetruefalse
falsetruefalsetruetrue
falsefalsefalsefalsetrue

&& is worked out before ||: just like * is worked out before + in maths (2 + 3 × 4 is 14, not 20), && is worked out before ||. This rule is called operator precedence (chapter 7 has the full list). So PHP reads $isFree && $isMember || $paysOnline as ($isFree && $isMember) || $paysOnline — "(free and member), or pays online". With Alex's values that's (false && false) || true, which is true: anyone paying online could book any slot, taken or not. Olivia's rule needs the brackets in a different place: $isFree && ($isMember || $paysOnline). Brackets (parentheses) always win, so put them wherever the grouping matters — even where you think PHP would get it right.

The double booking — and the fix
<?php
// Alex on Friday: slot taken, not a member, paid online
$isFree = false;
$isMember = false;
$paysOnline = true;
var_dump($isFree && $isMember || $paysOnline); // bool(true) — booked! (wrong)
var_dump($isFree && ($isMember || $paysOnline)); // bool(false) — correct

Name the parts: an even clearer fix is to give each part of a long condition its own named variable. Then the final line reads like the rule itself, and there's no grouping left to get wrong. The second code box below does this. It's a habit worth keeping: if you need to stop and think about a condition, split it up and name the pieces.

Even clearer: name the parts
<?php
$isFree = false;
$isMember = false;
$paysOnline = true;
$canPayForSlot = $isMember || $paysOnline;
$canBook = $isFree && $canPayForSlot;
var_dump($canBook); // bool(false)

Short-circuiting: PHP evaluates && and || from left to right, and stops as soon as the answer is certain. If the left side of && is false, the whole thing is false whatever the right side is, so PHP doesn't even look at the right side. If the left side of || is true, the answer is true, so the right side is skipped. This is called short-circuit evaluation. The code below proves it: the second check function never runs.

Short-circuiting: the right side is skipped
<?php
function check(string $name): bool
{
echo "checking $name\n";
return false;
}
var_dump(check("first") && check("second")); // only "checking first" is printed
var_dump(true || check("third")); // nothing is checked at all

Output: checking first, bool(false), bool(true). The second and third checks never run.

Using short-circuiting on purpose: this isn't just a speed trick — it lets you guard a risky check with a safe one. In $price !== null && $price > 0, the comparison $price > 0 only runs if $price isn't null. The same pattern protects division: $people !== 0 && $total / $people > 2000 never divides by zero. Put the cheap, safe check on the left and the check that depends on it on the right.

A safe check guarding a risky one
<?php
$price = null;
var_dump($price !== null && $price > 0); // bool(false): $price > 0 never runs
$people = 0;
$totalPence = 5000;
var_dump($people !== 0 && $totalPence / $people > 2000); // bool(false): no division by zero

and, or and xor — the word versions: PHP also has the words and and or. They do the same as && and ||, but with a much lower precedence — lower even than =. That causes a classic trap: $ok = true and false; stores true in $ok, because PHP reads it as ($ok = true) and false. There's also xor ("exclusive or"): true if exactly one side is true. Coding standards, and this course, use &&, || and ! only — and you'll know the trap if you meet and/or in old code.

The and/or trap
<?php
$ok = true and false; // read as: ($ok = true) and false
var_dump($ok); // bool(true) — surprise!
$ok = true && false; // && binds tighter than =
var_dump($ok); // bool(false)
var_dump(true xor true); // bool(false): xor needs exactly one true

Key Takeaway

&& (and) is true when both sides are true, || (or) when at least one is, ! (not) flips a value. && binds tighter than ||, so a && b || c means (a && b) || c — add brackets for the grouping you mean, or name the parts. && and || short-circuit: the right side is skipped once the answer is known, which lets a safe check guard a risky one. Avoid and/or: they bind looser than =.

Why This Matters

Every business rule at BookBay — who can book, who can cancel, when a refund applies — becomes a line of logical operators. One misplaced grouping turned "free and (member or online)" into a double booking on a busy Friday. Brackets and named parts make the code say exactly what Olivia said.

Short-circuiting is just as everyday: it's how Mia will safely check "is it there, and is it valid?" in one line, for the rest of the course.

Mia rewrites the slot check with named parts, and Friday's case now says false. Feeling good, she moves on to the confirmation message — which glues the customer's name, the time and the price into one sentence — and to merging Tom's new prices with the default price list. The message comes out fine. The prices don't: Tom's new haircut price simply vanishes. That's the next chapter.