Re: Proposal for RFC to remove undefined array index warning when used ina ternary
| From: | Claude Pache | Date: | Sun, 27 Feb 2022 23:03:27 +0000 |
| Subject: | Re: Proposal for RFC to remove undefined array index warning when used ina ternary | ||
| References: | 1 2 3 4 5 6 7 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-117157@lists.php.net to get a copy of this message | ||
> Le 27 févr. 2022 à 18:06, Robert Landers <landers.robert@gmail.com> a écrit :
>
>> $val = $array[?'a'][?'b'][?'c'] ?? 'default';
>>
>> Currently, the last example would need to be a rather unwieldy ternary:
>>
>> $val = (isset($array['a']) && isset($array['a']['b'])
>> &&
>> isset($array['a']['b']['c']) ?
>> $array['a']['b']['c'] : 'default';
>>
>
> I've been writing it like this:
>
> $val = (($array['a'] ?? [])['b'] ?? [])['c'] ??
> 'default';
>
> which is still unwieldy. I don't actually know if it is required to use []
> vs. null, but it makes sense to use an empty array to me.
>
Hi,
In PHP, you can write
$array['a']['b']['c'] ??
'default';. It works when either null or inexistant index is encountered at any
depth of the expression.
—Claude