phpPHP
Module 5: OperatorsBeginner45 min read

PHP Operators, == vs ===, Null Coalescing (?? / ??=) & Spaceship (<=>)

Master all PHP operators, why == vs === behave differently, null coalescing ?? and ??=, spaceship <=>, and operator precedence bugs.

Key Takeaways & Core Concepts
  • Null Coalescing (`??`, PHP 7.0): $name = $_GET['name'] ?? 'Guest'; (checks isset, no undefined-key warning!).
  • Null Coalescing Assignment (`??=`, PHP 7.4): $config['port'] ??= 8080;.
  • Spaceship (`<=>`, PHP 7.0): Returns -1, 0, or 1 (ideal for usort).

1. Loose (`==`) vs. Strict (`===`) Comparison

  • `==` performs type juggling before comparing (0 == "abc" was true in PHP 7, fixed to false in PHP 8, while 42 == "42" is still true).
  • `===` checks both value AND type with zero coercion. Always prefer `===` and `!==`!
1. Strict Comparison, ??= & Spaceship Operator
1<?php
2$user = null;
3$user ??= "Guest";
4echo "User: $user\n";
5echo "42 === '42': " . (42 === "42" ? "true" : "false") . "\n";
6echo "10 <=> 20: " . (10 <=> 20) . "\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
6 lines
Note: `??=` assigns `'Guest'` when `$user` is null; `===` rejects mismatched `int` vs `string`.

2. Modern PHP Operators

  • Null Coalescing (`??`, PHP 7.0): $name = $_GET['name'] ?? 'Guest'; (checks isset, no undefined-key warning!).
  • Null Coalescing Assignment (`??=`, PHP 7.4): $config['port'] ??= 8080;.
  • Spaceship (`<=>`, PHP 7.0): Returns -1, 0, or 1 (ideal for usort).

3. Precedence Pitfall

= has higher precedence than and/or, but lower than &&/||. Always use && and || for boolean logic!

Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)