On Tue, Oct 17, 2023, at 12:19, Saki Takamachi wrote:
>> What about a signature like:
>> 
>> ```php
>> array_first(array $array, mixed $value_if_missing = null);
>> ```
>> 
>> That would let you specify your own sentinel (or default) where appropriate, 
>> without losing the convenience of this function.
>
> This is a problem that should be addressed in your application.
>
> ```
> array_first($arr) ?? $initial
> ```
>
> I personally think we should make the effort to write it this way and 
> not have to support initial values ​​at the language level.

The problem Levi mentioned is that there's ambiguity in this construction: if 
the valid data domain for elements of `$arr` includes `null`, then you can't 
tell whether the null comes from the array being empty, or from its first value 
being null. In other words, there exists application code where using `??` in 
this way is unsuitable.

I can think of three approaches for dealing with this, resulting in application 
code like:

```
$value = array_first($arr, $default);

$value = count($arr) > 0 ? array_first($arr) : $default;

try {
  $value = array_first($arr);
} catch (OutOfBoundsException $e) {
  $value = $default;
}
```

I think the first of those - what I initially suggested - is the cleanest.

mjec

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

Reply via email to