Yeah, adding `?` after expressions gets weird because of ternary operators.

I do think the long-form `$foo[?'one'][?'two'][?'three']` is acceptable in
terms of developer experience considering it's not a super common scenario.
I'm not sure if that would be annoying to implement on the C side of things.

- Dan

On Sat, Mar 28, 2026 at 2:33 PM Rowan Tommins [IMSoP] <[email protected]>
wrote:

> On 27/03/2026 15:19, Alex Rock wrote:
> >
> > In that case, maybe reuse something similar to the null-safe operator ?
> >
> > Something like `$foo['bar']?`
> >
>
> I think even if you could make it work in the parser, it would be hard
> to make that read well with the ternary operator:
>
> $foo['a'] ? ['b'] ? ['c'] : ['d'];
>
>
> >     return $foo['one']?['two'];
>
> Looking at that, it's not obvious to me whether it's 'one' or 'two'
> which is optional.
>
> return $foo['one']  ?['two'];
> return $foo['one']?  ['two'];
>
>
> > And here it gets interesting:
> >
> >     return $foo['one']['two']?['three'];
> >     // is roughly equivalent to:
> >     if (!isset($foo['one']) {
> >     trigger_error('Undefined key "one" in ...', ...);
> >     }
> >     return $foo['one']['two']['three'] ?? null;
> >
>
> You can have the same ability with a ? inside the brackets, and without
> the ambiguity:
>
> // all three keys required to exist (as of PHP 9):
> return $foo['one']['two']['three'];
>
> // 'one' and 'two' required, 'three' optional:
> return $foo['one']['two'][?'three'];
>
> // both 'two' and 'three' optional:
> return $foo['one'][?'two'][?'three'];
>
> // optional all the way:
> return $foo[?'one'][?'two'][?'three'];
>
>
> This would maybe have similar short-cut semantics to ?->
>
> $foo = [];
> return $foo[?'one']['two'];
> // OK: the ? neutralises access to the missing section of the array,
> short-cutting to NULL
> // Similar to $foo?->bar->baz when $foo is NULL
>
> $foo = ['one' => []];
> return $foo[?'one']['two'];
> // Error: the ? had no effect, so we're trying to access non-existent
> key 'two' in the empty array $foo['one']
> // Similar to $foo?->bar->baz when $foo->bar exists
>
>
> But an RFC could pin down those details.
>
>
> --
> Rowan Tommins
> [IMSoP]
>

Reply via email to