Skip to content

Commit

Permalink
Add null coalescing section
Browse files Browse the repository at this point in the history
  • Loading branch information
leocarmo committed Apr 9, 2020
1 parent 8f6c4ee commit 2a33156
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 2a33156

Please sign in to comment.