# RFC: array_first() and array_last()

- Status: Implemented (PHP 8.5)
- Authors: Niels Dossche, nielsdos@php.net
- Date: 2025-03-31
- Version: 1.0
- Target: 8.5
- Implementation: https://github.com/php/php-src/commit/168343d2e811fe0f2152d39a8f88557cc0b35c86
- Original: https://wiki.php.net/rfc/array_first_last
- Page: https://externals.io/rfc/array_first_last
- 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

## Votes

### Add array_first() and array_last()? (closed)

Yes: 35 · No: 0

Voters: alcaeus (Yes), alec (Yes), ashnazg (Yes), ayesh (Yes), bwoebi (Yes), crell (Yes), cschneid (Yes), daniels (Yes), davey (Yes), derick (Yes), devnexen (Yes), dharman (Yes), edorian (Yes), ericmann (Yes), galvao (Yes), girgias (Yes), ilutov (Yes), jimw (Yes), josh (Yes), jwage (Yes), kalle (Yes), levim (Yes), mauricio (Yes), mbeccati (Yes), mfonda (Yes), nicolasgrekas (Yes), nielsdos (Yes), nikic (Yes), pmjones (Yes), ramsey (Yes), santiagolizardo (Yes), sebastian (Yes), sergey (Yes), theodorejb (Yes), weierophinney (Yes)

## Discussions on the mailing list

- [\[VOTE\] array_key_first(), array_key_last(), array_value_first(), array_value_last()](https://externals.io/message/102663.md) — started on 2018-07-09, 34 messages
- [Two new functions array_first() and array_last()](https://externals.io/message/121313.md) — started on 2023-10-14, 46 messages
- [\[RFC\] \[Discussion\] array_first() and array_last()](https://externals.io/message/127047.md) — started on 2025-04-05, 22 messages
- [\[RFC\] \[Vote\] array_first() and array_last()](https://externals.io/message/127171.md) — started on 2025-04-22, 3 messages

---

## Introduction

In PHP 7.3, we got array\_key\_first() and array\_key\_last() to get the first and last keys from an array. What we don't have yet is a way to get the first and last values of an array. This is harder than you may think because:

- The array keys are not necessarily integers, not necessarily starting with 0, etc...
- Existing “tricks” like reset() and end() are semantically the wrong approach because they modify the “internal iterator” of the array. Furthermore, it also does not work properly on all types of expressions (e.g. an array returned from a function / plain array can cause a notice due to the by-ref argument).
- Using `$array[array_key_first($array)]` is cumbersome

## Proposal

```php
function array_first(array $array): mixed {}
function array_last(array $array): mixed {}
```

These functions return the first/last value of the array, respectively. I.e. these functions are equivalent to `$array[array_key_first($array)]` and similarly for the last element. Alternatively, for array\_first(), this could be written as a foreach loop where the first iteration returns.

If the array value to be returned is a reference, it is dereferenced automatically.

### Behaviour on empty arrays

[The RFC introducing the key functions](https://externals.io/rfc/array_key_first_last) also proposed to implement these functions, but the vote for those failed. The main complaint seemed to be the behaviour on failure.

Should it throw on an empty array or should it return NULL? Theoretically NULL can be a valid value from an array, and therefore returning NULL does not allow distinguishing between an empty array and a NULL value. However, there are still strong arguments in favor of using NULL:

- Consistent with `$array[array_key_first($array)]`, i.e. accessing a non-existent key gives NULL
- Consistent with `array_find($arr, fn () => true)` returning NULL on no match
- Consistent with `array_shift()` and `array_pop()` returning NULL on empty arrays (also about retrieving first/last element, but with modification)
- Consistent with common framework helpers like `Arr::first()`
- NULL is a rare legitimate value, so the potential for clashing is low
- Works nicely with “??” operator
- If it were to throw an exception instead, then you would need to check the size of the array upfront. Similarly, if NULL is a legit value then you can just check the array size upfront too.

Another interesting idea is to add an optional “$default” argument (i.e. if provided return the default; otherwise throw). However, since PHP arrays are untyped it's often hard to define something meaningful as a sentinel value. There is also no precedent for this design choice for the array functions. Furthermore, when a programmer reads `array_first($somevar, $someothervar)`, it looks weird unless you already know that `$somevar` is an array and `$someothervar` is a fallback value. It just looks unintuitive.

### Naming

Why array\_first/array\_last instead of array\_value\_first/array\_value\_last? First, this is consistent with how (most) array functions are named: the ones that work on keys have “key” in the name, and the ones that work on values don't have “value” in the name. Think about array\_find, array\_find\_key, etc. Second, the shorter name is less verbose and intuitively at least I understood this is about the value.

### Fibers

In the [discussion thread from 2023](https://externals.io/message/121313) there was some confusion on how this interacted with Fibers. TL;DR: The concern was that if you have a call for array\_key\_first() followed by array\_first() that the result could be inconsistent if a Fiber interrupted the execution. This is however based on the false premise that Fibers are threads, in fact they are not. This situation cannot happen.

### Why include this in the engine rather than userland?

Three main reasons:

1. Consistency with array\_key\_first()/array\_key\_last().
2. The cost/maintenance burden is practically zero, the implementation is stupidly simple (4 lines trivial argument parsing boilerplate, 3 lines actual code; per function).
3. 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.

### Examples

Here are some code examples of how to use these functions:

```php
array_first(["single element"]); // "single element"
array_last(["single element"]); // "single element"
 
array_first([]); // NULL
array_last([]); // NULL
 
array_first([1 => 'a', 0 => 'b', 3 => 'c', 2 => 'd']); // 'a'
array_last([1 => 'a', 0 => 'b', 3 => 'c', 2 => 'd']); // 'd'
 
$str = "hello";
array_first([&$str, false]); // "hello" (no ref)
array_last([false, &$str]); // "hello" (no ref)
```

## Backward Incompatible Changes

If anyone defined array\_first() or array\_last() in their global scope, then they need to guard it now with function\_exists or throw it away because of the name clash. Although it should be noted that the global namespace is normally reserved for PHP's usage.

## Proposed PHP Version(s)

Next PHP 8.x, i.e. PHP 8.5 at the time of writing.

## RFC Impact

### To Existing Extensions

These two new functions are added to ext-standard, where array\_key\_first() and array\_key\_last() also live.

## Unaffected PHP Functionality

No changes to existing PHP functionality.

## Proposed Voting Choices

2/3rd yes/no vote.

**Vote: Add array\_first() and array\_last()?** — Yes: 35 · No: 0 (closed)

## Patches and Tests

PR: <https://github.com/php/php-src/pull/18210>

## Implementation

After the project is implemented, this section should contain

1. the version(s) it was merged into: 8.5
2. a link to the git commit(s): <https://www.php.net/manual/en/function.array-first.php> and <https://www.php.net/manual/en/function.array-last.php> added in <https://github.com/php/php-src/commit/168343d2e811fe0f2152d39a8f88557cc0b35c86>
3. a link to the PHP manual entry for the feature: <https://github.com/php/doc-en/pull/4925>
4. a link to the language specification section (if any): N/A

## References

Current discussion: <https://externals.io/message/127047>

### Prior Work

- Proposal from 2023 discussing these new functions: <https://externals.io/message/121313>
- RFC that introduced array\_key\_first() and array\_key\_last(): [https://wiki.php.net/rfc/array\_key\_first\_last](https://externals.io/rfc/array_key_first_last) with discussion: <https://externals.io/message/102663>

## Rejected Features

None yet.

## Changelog

- 1.0: Initial version under discussion
