# [RFC] [Discussion] array_first() and array_last()

- Thread: https://externals.io/message/127047
- Original archive: https://news-web.php.net/php.internals/127047
- Started by Niels Dossche on 2025-04-05T15:51:27+00:00
- Messages: 22
- RFC: array_first() and array_last() (Implemented (PHP 8.5)) — https://externals.io/rfc/array_first_last.md
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #127047 — Niels Dossche — 2025-04-05T15:51:27+00:00

URL: https://externals.io/message/127047#127047

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

---

## #127048 — Claude Pache — 2025-04-05T18:00:23+00:00

URL: https://externals.io/message/127047#127048 · In reply to: #127047

> Le 5 avr. 2025 à 17:51, Niels Dossche <dossche.niels@gmail.com> a écrit :
> 
> 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


Hi Niels,

It is reasonable. I have a userland implementation of that in my codebase since long ago.

You missed the following point when discussing the behaviour for empty array:

* Consistent with `array_shift()` and `array_pop()`, which are also about retrieving the first, respectively the last element of an array.

—Claude

---

## #127049 — Niels Dossche — 2025-04-05T18:04:24+00:00

URL: https://externals.io/message/127047#127049 · In reply to: #127048

> Hi Niels,
> 
> It is reasonable. I have a userland implementation of that in my codebase since long ago.
> 
> You missed the following point when discussing the behaviour for empty array:
> 
> * Consistent with `array_shift()` and `array_pop()`, which are also about retrieving the first, respectively the last element of an array.

Hi Claude

Good point, I'll add that as well, thanks.
There are probably even more arguments that can be made :)

> 
> —Claude

Niels

---

## #127061 — Juris Evertovskis — 2025-04-06T17:06:25+00:00

URL: https://externals.io/message/127047#127061 · In reply to: #127047

> 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

Hi,

Do you think it would be hard or wrong to add `array_nth`? I've had more 
trouble with that as the in-place implementation is usually pretty 
unreadable, e.g.

     array_slice(array_values($array), $offset, 1)[0] ?? null

I understand this need is less common, especially compared to 
`array_first`. But I also suspect that an in-engine implementation might 
have more performance gains compared to an userland one.

BR,
Juris

---

## #127062 — Bilge — 2025-04-06T19:04:33+00:00

URL: https://externals.io/message/127047#127062 · In reply to: #127061

> I also suspect that an in-engine implementation might have more 
> performance gains compared to an userland one.

That applies to literally anything, obviously; one less layer of 
abstraction is always more efficient. That's therefore not a reason to 
add something to the engine. I suggest first proving there is a 
legitimate need.

Cheers,
Bilge

---

## #127063 — Ayesh Karunaratne — 2025-04-07T00:47:35+00:00

URL: https://externals.io/message/127047#127063 · In reply to: #127062

> 
> ... [snip] I suggest first proving there is a
> legitimate need.

I did a quick GitHub search for a common pattern of accessing an array
value by using the `array_key_first` and `array_key_last` functions:

```php
$value = $arr[array_key_first($results)];
```

 - `[array_key_first(`: over 3,700 results[^1]
 - `[array_key_last(`: over 4,300 results[^2]

All of these hits can benefit from the proposed `array_first` and `array_last`.

---

## #127064 — Larry Garfield — 2025-04-07T03:39:51+00:00

URL: https://externals.io/message/127047#127064 · In reply to: #127063

> > […]
>
> I did a quick GitHub search for a common pattern of accessing an array
> value by using the `array_key_first` and `array_key_last` functions:
>
> ```php
> $value = $arr[array_key_first($results)];
> ```
>
>  - `[array_key_first(`: over 3,700 results[^1]
>  - `[array_key_last(`: over 4,300 results[^2]
>
> All of these hits can benefit from the proposed `array_first` and `array_last`.

Just registering that I am all for this RFC and look forward to using it.

--Larry Garfield

---

## #127065 — Bilge — 2025-04-07T04:43:11+00:00

URL: https://externals.io/message/127047#127065 · In reply to: #127063

> > […]
> I did a quick GitHub search for a common pattern of accessing an array
> value by using the `array_key_first` and `array_key_last` functions:
>
> ```php
> $value = $arr[array_key_first($results)];
> ```
>
>   - `[array_key_first(`: over 3,700 results[^1]
>   - `[array_key_last(`: over 4,300 results[^2]
>
> All of these hits can benefit from the proposed `array_first` and `array_last`.

To be clear, I wasn't disputing first/last, but nth, but thanks for the 
insights!

Cheers,
Bilge

---

## #127068 — Niels Dossche — 2025-04-07T19:31:23+00:00

URL: https://externals.io/message/127047#127068 · In reply to: #127061

> 
> Do you think it would be hard or wrong to add `array_nth`? I've had more trouble with that as the in-place implementation is usually pretty unreadable, e.g.
> 
>     array_slice(array_values($array), $offset, 1)[0] ?? null
> 
> I understand this need is less common, especially compared to `array_first`. But I also suspect that an in-engine implementation might have more performance gains compared to an userland one.
> 

This is not hard to add. For packed arrays this can be done in O(1) time, for non-packed arrays in O(n) worst case.
If added, it's best to add the pair array_nth() & array_nth_key() together IMO.
However, it's not something I ever really needed nor something that I have seen a demand for.
I think this could be left for the future for follow-up work.

Kind regards
Niels

---

## #127071 — Daikaras — 2025-04-08T08:53:07+00:00

URL: https://externals.io/message/127047#127071 · In reply to: #127047

> 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


-1 because returning `null` for empty arrays is still wrong. Whatever 
similar behavior exists should be corrected to throw `ValueError` in the 
future. Just my 2c.

---

## #127072 — Levi Morrison — 2025-04-08T16:37:04+00:00

URL: https://externals.io/message/127047#127072 · In reply to: #127047

>
> 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.

---

## #127073 — Rob Landers — 2025-04-08T16:54:11+00:00

URL: https://externals.io/message/127047#127073 · In reply to: #127071

> 
> > […]
> 
> 
> -1 because returning `null` for empty arrays is still wrong. Whatever 
> similar behavior exists should be corrected to throw `ValueError` in the 
> future. Just my 2c.
> 

I’ve always viewed arrays as an infinite field of nulls. The only time this isn’t true is when you use `array_key_exists()` or care about the warnings (which make it less useful, IMHO). When you treat it as an infinite field of nulls, you get some interesting mathematical/computational properties you can exploit. Trying to treat it as a map/indexed-array is when you start running into weird problems.

— Rob

---

## #127074 — Andreas Hennings — 2025-04-08T18:24:24+00:00

URL: https://externals.io/message/127047#127074 · In reply to: #127063

>
> > […]
>
> I did a quick GitHub search for a common pattern of accessing an array
> value by using the `array_key_first` and `array_key_last` functions:
>
> ```php
> $value = $arr[array_key_first($results)];
> ```
>
>  - `[array_key_first(`: over 3,700 results[^1]
>  - `[array_key_last(`: over 4,300 results[^2]
>
> All of these hits can benefit from the proposed `array_first` and `array_last`.

(I used the wrong reply button earlier..)

I suspect this is just the tip of the iceberg. You should look for
 `reset()` and `end()`.
I get 336K when I look for "/(= |return |\(|\[)(reset|end)\(\$/ language:PHP".
I get 8.3K when I look for "/\[array_key_(first|last)\(/ language:PHP".

There are more matches for "/reset\(" and "/end\(", but we only want
matches where the return value is used.

And indeed I want to never have to use `reset()` and `end()` again!
I don't recall when I ever intentionally used the internal array
pointer. Only as a workaround to get a first or last element.

-- Andreas

---

## #127075 — Andreas Hennings — 2025-04-08T18:25:18+00:00

URL: https://externals.io/message/127047#127075 · In reply to: #127072

>
> 
> > […]
>
> 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

---

## #127076 — Claude Pache — 2025-04-08T18:46:16+00:00

URL: https://externals.io/message/127047#127076 · In reply to: #127047

> Le 5 avr. 2025 à 17:51, Niels Dossche <dossche.niels@gmail.com> a écrit :
> 
> 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


Hi,

I think that this argument is not convincing, and even counterproductive:

* `NULL` is a rare legitimate value, so the potential for clashing is low

First, it says that it is a “rare” legitimate value, which one can disagree with. (I do disagree.)

Second, the way it is formulated, it implies that, when `null` is used in array, there will be “clashing”, which is not necessarily the case. (I consider that there is almost never a clash, because it is rarely useful to make the difference between an explicit `null` and a missing value, and, when it is useful, you have almost surely already checked for an empty array upfront.)

I suggest to replace that argument with the two following ones, that doesn’t treat arrays with `NULL` as second class citizens:

* Semantically, `NULL` represents a missing value. Returning `NULL` from an empty array is not semantically incorrect, but it means that the function doesn’t differentiate between a implicit missing value (empty array) and an explicit missing value (array with `NULL` as its first/last element).

* In the relatively rare cases you do want to make the difference between an empty array and an array that starts/ends with NULL, you can (and should) just check for empty array upfront.

-------

One more thing. On https://www.php.net/, I read: “Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.” (emphasis added). If we were to design some new perfect language, we might consider making `array_first()` (or equivalent) choke on empty arrays. But given the current state of the affairs, the pragmatic thing to do is to pave the cowpath.

—Claude

---

## #127077 — Larry Garfield — 2025-04-08T20:48:32+00:00

URL: https://externals.io/message/127047#127077 · In reply to: #127047

> 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

To add another argument: the `reset()` workaround doesn't work with a readonly array property, because it does modify the array's internal pointer.

https://3v4l.org/Zo5dZ

Yes, I have in fact run into this situation in real code, which led me to use the $a[array_key_first($a)] dance instead.  I'd love to replace it with a single call.

--Larry Garfield

---

## #127078 — Niels Dossche — 2025-04-08T22:21:57+00:00

URL: https://externals.io/message/127047#127078 · In reply to: #127071

> 
> > […]
> 
> 
> -1 because returning `null` for empty arrays is still wrong. Whatever similar behavior exists should be corrected to throw `ValueError` in the future. Just my 2c.
> 

I think consistency is very important, hence I will stick to my reasoning why returning `NULL` is the right thing at the moment.
If the behaviour of array functions on empty arrays is ever revised in the future, then we should keep everything consistent. So e.g. if a _future_ RFC decides to make array access throw instead of yield NULL, then this should affect array_{first,last} too IMO. However, that's not for now, that's a lot of ifs and hypothetical future development. That discussion should happen in the future elsewhere.

---

## #127079 — Niels Dossche — 2025-04-08T22:21:57+00:00

URL: https://externals.io/message/127047#127079 · In reply to: #127071

> 
> > […]
> 
> 
> -1 because returning `null` for empty arrays is still wrong. Whatever similar behavior exists should be corrected to throw `ValueError` in the future. Just my 2c.
> 

I think consistency is very important, hence I will stick to my reasoning why returning `NULL` is the right thing at the moment.
If the behaviour of array functions on empty arrays is ever revised in the future, then we should keep everything consistent. So e.g. if a _future_ RFC decides to make array access throw instead of yield NULL, then this should affect array_{first,last} too IMO. However, that's not for now, that's a lot of ifs and hypothetical future development. That discussion should happen in the future elsewhere.

---

## #127080 — Niels Dossche — 2025-04-08T22:26:31+00:00

URL: https://externals.io/message/127047#127080 · In reply to: #127076

> Hi,
> 
> I think that this argument is not convincing, and even counterproductive:
> 
> * `NULL` is a rare legitimate value, so the potential for clashing is low
> 
> First, it says that it is a “rare” legitimate value, which one can disagree with. (I do disagree.)
> 

I think it's a matter of phrasing, but I agree that it can be more nuanced.

> Second, the way it is formulated, it implies that, when `null` is used in array, there will be “clashing”, which is not necessarily the case. (I consider that there is almost never a clash, because it is rarely useful to make the difference between an explicit `null` and a missing value, and, when it is useful, you have almost surely already checked for an empty array upfront.)
> 
> I suggest to replace that argument with the two following ones, that doesn’t treat arrays with `NULL` as second class citizens:
> 
> * Semantically, `NULL` represents a missing value. Returning `NULL` from an empty array is not semantically incorrect, but it means that the function doesn’t differentiate between a implicit missing value (empty array) and an explicit missing value (array with `NULL` as its first/last element).
> 
> * In the relatively rare cases you do want to make the difference between an empty array and an array that starts/ends with NULL, you can (and should) just check for empty array upfront.
> 

That's indeed a bit better worded and more nuanced. I might adapt the RFC text a bit; although in the end it kinda means the same thing anyway.

> -------
> 
> One more thing. On https://www.php.net/, I read: “Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.” (emphasis added). If we were to design some new perfect language, we might consider making `array_first()` (or equivalent) choke on empty arrays. But given the current state of the affairs, the pragmatic thing to do is to pave the cowpath.

I agree. I value consistency; we have too much inconsistency already in PHP anyway, let's not add more (unless we would have a very very good reason to do so; but that's not in this case IMO).

---

## #127158 — Niels Dossche — 2025-04-20T15:30:37+00:00

URL: https://externals.io/message/127047#127158 · In reply to: #127047

> 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
> 


Hi

I'll be putting this to vote on Tuesday 22nd if no one has complaints.

Kind regards
Niels

---

## #127173 — Levi Morrison — 2025-04-22T16:51:55+00:00

URL: https://externals.io/message/127047#127173 · In reply to: #127158

>
> 
> > […]
>
>
> Hi
>
> I'll be putting this to vote on Tuesday 22nd if no one has complaints.
>
> Kind regards
> Niels

In the section "Why include this in the engine rather than
userland?", there is this comment:

> Very fast implementation, faster than a PHP implementation in
> my brief tests. Further optimization is possible by
> implementing an additional frameless variant, but that's
> future material if ever necessary/interesting.

I think array_first and array_last are good candidates for being
frameless, as they are quite cheap functions, so lowering their
overhead further is nice. Additionally, they don't call into
user code, so the chance that this function will be included in
a stack trace is quite low. These arguments also apply to
array_key_first and array_key_last, of course.

I don't think it blocks this RFC in any way, and could be made
frameless after the vote--I just wanted to bring up that I think
they _should_ be frameless if they get accepted (and update
array_key_first/array_key_last to be frameless too).

---

## #127166 — Niels Dossche — 2025-04-22T16:57:51+00:00

URL: https://externals.io/message/127047#127166 · In reply to: #127173

> I don't think it blocks this RFC in any way, and could be made
> frameless after the vote--I just wanted to bring up that I think
> they _should_ be frameless if they get accepted (and update
> array_key_first/array_key_last to be frameless too).

Hi

Indeed, we have added frameless versions of functions before, without a RFC.
This is not a problem because this is just like any other optimization that we PR.
Note that we always need to have _both_ a normal handler and a frameless handler, so it's not about _converting_ but about adding another handler (just making sure we're on the same page :-)).

Kind regards
Niels
