Lesson 5 — Fundamentals

Operators

PHP provides arithmetic, comparison, logical, and assignment operators, plus a few PHP-specific operators worth knowing well, like the null coalescing operator.

Comparison: == vs ===

Loose equality (==) compares values after converting types if needed; strict equality (===) requires both the value and the type to match exactly. This distinction causes more bugs in PHP than almost anything else for beginners.

PHP — Loose vs strict comparison
var_dump(0 == "abc");   // false in PHP 8+, but was true in PHP 7 — a classic gotcha
var_dump("5" == 5);      // true — loose comparison converts types
var_dump("5" === 5);     // false — different types, strict comparison fails

The Null Coalescing Operator

The ?? operator returns its left operand if it exists and isn't null, otherwise it returns the right operand — a clean shorthand for providing default values.

PHP — Null coalescing operator
$username = $_GET['username'] ?? 'Guest';
echo "Welcome, $username";

Common Mistakes

  • Using == when === was intended, especially in security-sensitive comparisons like checking a hash or token.
  • Forgetting that PHP's comparison behaviour between strings and numbers has changed across versions — always test on the version you're targeting.
  • Writing a longer isset() check where the null coalescing operator (??) would be clearer and shorter.
  • Confusing the null coalescing operator (??) with the ternary operator (?:), which behave similarly but check different conditions.

Professional Tip

Default to === unless you have a specific, well-understood reason to use ==. Strict comparison avoids an entire category of subtle bugs caused by PHP's type juggling.

Your Turn

Write a script that safely reads a 'theme' value from an array (which may or may not be set) using the null coalescing operator, defaulting to 'light' if it's missing.

Mini Quiz

What does the ?? (null coalescing) operator do?