PHP 7: Maintaining and Upgrading Legacy Apps · PHP 7 Language Essentials

Null Coalescing, Spaceship and Other Operators

Use ??, <=>, ??= and other PHP 7 conveniences.

PHP 7.0 added the null coalescing operator ?? (returns the left side if it exists and isn't null, without notices) and the spaceship operator <=> for three-way comparison (ideal for usort). PHP 7.4 added ??=. These replace verbose isset() ternaries and comparison functions common in PHP 5 code.

<?php
// PHP 5 style
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
// PHP 7
$page = (int) ($_GET['page'] ?? 1);

usort($products, function ($a, $b) {
    return [$a['category'], $b['price']] <=> [$b['category'], $a['price']];  // category asc, price desc
});

$config['timeout'] ??= 30;   // PHP 7.4

Common pitfalls

  • ?? only checks null/undefined — an empty string or 0 is returned as-is.
  • Using ?: (Elvis) when you meant ??; ?: treats falsy values like 0 as missing.
  • Comparing arrays with <=> element by element without realizing order matters.

Key points

  • ?? replaces isset ternaries
  • <=> simplifies sort callbacks
  • ??= assigns defaults (7.4)

Further reading: PHP manual: comparison operators

Practice questions

What's the difference between $a ?? 'x' and $a ?: 'x'?

Answer

?? falls back only when $a is null or undefined (no notice). ?: falls back when $a is falsy (0, '', '0', [], false) and raises a notice if $a is undefined.

What does 1 <=> 2 return?

Answer

-1. The spaceship operator returns -1, 0 or 1 when the left side is less than, equal to, or greater than the right side.

Open in the app to mark lessons complete, take notes and track your progress.