Last active
October 29, 2024 15:07
-
-
Save twysto/b615f8d4f61aaac608894211ba66488b to your computer and use it in GitHub Desktop.
Example usage of the "Null Coalescing Assignment Operator"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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