diff --git a/README.md b/README.md index d305e14..b461793 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ * [Use default arguments instead of short circuiting or conditionals](#use-default-arguments-instead-of-short-circuiting-or-conditionals) 3. [Comparison](#comparison) * [Use identical comparison](#use-identical-comparison) + * [Null coalescing operator](#null-coalescing-operator) 4. [Functions](#functions) * [Function arguments (2 or fewer ideally)](#function-arguments-2-or-fewer-ideally) * [Function names should say what they do](#function-names-should-say-what-they-do) @@ -440,6 +441,28 @@ The comparison `$a !== $b` returns `TRUE`. **[⬆ back to top](#table-of-contents)** +### Null coalescing operator + +Null coalescing is a new operator [introduced in PHP 7](https://www.php.net/manual/en/migration70.new-features.php). The null coalescing operator `??` has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with `isset()`. It returns its first operand if it exists and is not `null`; otherwise it returns its second operand. + +**Bad:** + +```php +if (isset($_GET['name'])) { + $name = $_GET['name']; +} elseif (isset($_POST['name'])) { + $name = $_POST['name']; +} else { + $name = 'nobody'; +} +``` + +**Good:** +```php +$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody'; +``` + +**[⬆ back to top](#table-of-contents)** ## Functions