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
- What are typed properties in PHP 7.4?
- What are arrow functions in PHP 7.4 and how do they differ from closures?
- What were the headline improvements of PHP 7.0 over PHP 5.6?
- Explain the `Throwable`, `Error` and `Exception` hierarchy introduced in PHP 7.
- What are nullable types in PHP 7.1?
- How do return type declarations work in PHP 7?
- Explain scalar type declarations and coercive vs strict mode in PHP 7.
- What are the main breaking changes when upgrading from PHP 7.4 to 8.0?