Re: Two new functions array_first() and array_last()

From: Date: Tue, 17 Oct 2023 16:34:38 +0000
Subject: Re: Two new functions array_first() and array_last()
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-121354@lists.php.net to get a copy of this message
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

« previous php.internals (#121354) next »