Skip to content

Instantly share code, notes, and snippets.

@Amegatron
Created May 29, 2026 09:05
Show Gist options
  • Select an option

  • Save Amegatron/06da8770e46e116b05f1c290cb0d56fc to your computer and use it in GitHub Desktop.

Select an option

Save Amegatron/06da8770e46e116b05f1c290cb0d56fc to your computer and use it in GitHub Desktop.
Null-coalescing associative array elements example
<?php
function givesNull(): ?int {
return null;
}
function shouldAdd(): bool {
return false;
}
$nullValue = null;
$a = [
'test1' ?=> 12312,
'test2' ?=> $nullValue,
'test3' ?=> givesNull(),
'test4' ?=> "test string",
'test5' ?=> null,
'test7' ?=> shouldAdd() ? "added" : null,
'test8' ?=> [
'sub-key-1' ?=> 'test',
'sub-key-2' ?=> givesNull(),
],
];
var_dump($a);
/*
Output:
array(3) {
["test1"]=>
int(12312)
["test4"]=>
string(11) "test string"
["test8"]=>
array(1) {
["sub-key-1"]=>
string(4) "test"
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment