Skip to content

Instantly share code, notes, and snippets.

@twysto
Last active October 29, 2024 15:07
Show Gist options
  • Save twysto/b615f8d4f61aaac608894211ba66488b to your computer and use it in GitHub Desktop.
Save twysto/b615f8d4f61aaac608894211ba66488b to your computer and use it in GitHub Desktop.
Example usage of the "Null Coalescing Assignment Operator"
<?php
$arr = [
'a' => 'xyz',
'b' => null,
'c' => 0,
];
// Rather than writing:
//
// if (
// ! isset($arr['x'])
// || is_null($arr['x'])
// ) {
// $arr['x'] = 0;
// }
//
// Or (better):
//
// if (empty($arr['x'])) {
// $arr['x'] = 0;
// }
//
// Why not just use the power of the "Null Coalescing Operator"?
$arr['a'] = $arr['a'] ?? 0;
// Or even better, you can use the "Null Coalescing ``Assignment`` Operator".
$arr['b'] ??= 0;
$arr['c'] ??= 0;
$arr['d'] ??= 0;
print_r($arr);
// Output:
//
// Array
// (
// [a] => xyz
// [b] => 0
// [c] => 0
// [d] => 0
// )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment