I've been finding that I'm writing a lot of code like this:
$customData1 = $user['custom_data_1'] ?? null;
$customData2 = $user['custom_data_2'] ?? null;
$customData3 = $user['custom_data_3'] ?? null;
It seems like there should be some kind of simpler syntax for this.
I'd love for this to work without error:
$customData1 = $user['custom_data_1'];
And $customData1 would be null if the index is not defined. But this presents a PHP error. Is there something similar to this:
$customData1 = $user['custom_data_1']?;
I understand using ?? when the fallback is something less unusual, but null is quite common and I don't see why there isn't a default for this operator.
I know I could also do this:
$user = (object) $user;
$customData1 = $user->custom_data_1;
$customData2 = $user->custom_data_2;
$customData3 = $user->custom_data_3;
But this kind of goes beyond what I'm actually trying to find an answer for.
?? null, you're explicitly stating that you expect the index to not exist. Explicit code is always better. If PHP didn't throw a warning when a key didn't exist, then you could easily miss typos on keys, among other things. Now in most cases you're better off using objects/DTOs (very basic objects), so your properties would exist anyway and have a default value.$customData1 = @$user['custom_data_1'];(which is pretty much what you're looking for). But, seriously, don't :)