Re: [RFC] [Discussion] array_first() and array_last()

From: Date: Tue, 08 Apr 2025 18:25:18 +0000
Subject: Re: [RFC] [Discussion] array_first() and array_last()
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-127075@lists.php.net to get a copy of this message
On Tue, 8 Apr 2025 at 18:38, Levi Morrison <levi.morrison@datadoghq.com> wrote: > > On Sat, Apr 5, 2025 at 9:51 AM Niels Dossche <dossche.niels@gmail..com> wrote: > > > > Hi internals > > > > I'm opening the discussion for the RFC "array_first() and array_last()".. > > https://wiki.php.net/rfc/array_first_last > > > > Kind regards > > Niels > > I dislike all the functions where null is a valid value, which > can > also be confused with an error in the operation. > > However, this is kind of in the grey area for me, because we do have > plenty of tools to avoid the error condition. Of course there's the > simple if: > > if (!empty($array) { > $first = array_first($array); > } > > And if we have a default value that could be used: > > $first = !empty($array) ? array_first($array) : $default; > > I would prefer a better design tool than returning null, but being > honest, neither of these are too bad. As long as our documentation for > these functions are helpful but concise about showing how to work > around these edges, then I may be convinced to vote yes despite the > design. (I used the wrong reply button earlier) The problem with the above solutions is that you need to repeat the array expression. For a simple variable that is ok, but for a call, not so much. So it is not good for nested expressions, you need to introduce a local variable. (which some believe you should do anyway, but...) One way to get a custom unique "empty" value would be this: $zilch = new \stdClass(); $first = array_first(some_lengthy_expression() ?: [$zilch]); if ($first === $zilch) { ... } We will know for sure that $zilch cannot be a pre-existing array value. In a lot of cases we already know that the array does not contain NULL, then it works fine as a default. -- Andreas

« previous php.internals (#127075) next »