On 27 February 2022 00:04:58 CET, Kamil Tekiela <tekiela...@gmail.com> wrote:
>I just wanted to add that the following
>
>$name = $_POST['name'] ?: 'Default Name';
>
>with existence check would be
>
>$name = $_POST['name'] ?? null ?: 'Default Name';
>
>You don't need empty().
>
>I would be against changing the behaviour of elvis/ternary operator.
>However, I remember seeing past suggestions to implement another operator.
>One that would fill the gap between null-coalesce and elvis operators. If I
>recall correctly, most of the time, these proposals end in consensus that
>such operator isn't really needed. See
>https://externals.io/message/89292#89292 and
>https://externals.io/message/101606#101610
>Maybe, it would be worthwhile to refresh a discussion about adding such
>operator to the PHP language?

I think that what would be needed here is another proposal from this discussion,
something like a null-safe operator but for array access.

From a different thread about this:

On 15 February 2022 16:50:48 CET, Rowan Tommins <rowan.coll...@gmail.com> wrote:
>I seem to remember someone proposing an explicit operator for "this array 
>dimension might not exist", something like this:
>
>if ( $array[?'key'] === true )
>
>Which would translate to:
>
>if ( (array_key_exists('key', $array) ? $array['key'] : null) === true )

I would propose to extend this still to mean:
`if((($array !== null && array_key_exists('key', $array)) ? $array['key'] : 
null) === true)`

This combines the above proposal with the behaviour of the nullsafe operator
`?->`, allowing to signal that the array may be null or that the key may not be 
set.

This allows the requested functionality without warnings/notices:

$name = $_POST[?'name'] ?? 'Default Name';

But also allows accessing arrays with multiple, possibly defined dimensions:

$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';

The fact that the new syntax would also allow $array to be null may be 
undesirable in some cases, but I don't know if we can define the semantics in a 
better way.
(Also, in some cases this may actually be useful, eg. when mixing ?-> and the 
new
[?...] syntax.)

I am not sure if the exact syntax/semantics proposed here are the best
solution, but I would argue that the fact that this seems to be a recurring 
topic
calls for a solution in that general direction.

Regards,
Mel

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to