PHP 7 interview question · Most asked

What does the null coalescing operator `??` do, and how is it different from `isset()` with a ternary?

Summary

$a ?? $b returns $a if it exists and isn't null, otherwise $b, without emitting notices. It's shorthand for isset($a) ? $a : $b.

Longer Answer

It works with nested array keys and object properties: $config['db']['host'] ?? 'localhost'. It can be chained ($a ?? $b ?? $c). PHP 7.4 added the assignment form ??=. Unlike ?:, it doesn't treat 0, '' or false as missing.

Code Example

<?php
$page = $_GET['page'] ?? 1;
$host = $config['db']['host'] ?? getenv('DB_HOST') ?? 'localhost';
$options['timeout'] ??= 30; // PHP 7.4

Key Points

  • Equivalent to isset($x) ? $x : $default
  • No undefined index notices
  • Chainable
  • ??= (7.4) assigns if null

More most-asked PHP 7 questions

← All PHP 7 questions