PHP example

How to get the first and last element of an array in PHP

7 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

On PHP 8.5, use array_first($arr) and array_last($arr). They work on lists and associative arrays alike, leave the array untouched, and return null for an empty array. For the keys, use array_key_first($arr) and array_key_last($arr) (PHP 7.3). On PHP 7.3 to 8.4, get a value with $arr[array_key_first($arr)] after checking that the array isn't empty. Don't use $arr[0]: the first element's key is not always 0.

A PHP array is an ordered map, so "the first element" means the first one in insertion order, whatever its key is. That is why the obvious $arr[0] breaks on associative arrays and on lists that went through unset() or array_filter(). PHP 8.5 added array_first() and array_last() for exactly this job; older code uses array_key_first(), reset() and end(), or array_slice(). They differ in what they give back for an empty array (null, false or []) and in whether they touch the array. The sections below cover each one, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1array_first() and array_last() (PHP 8.5)Recommended

array_first() returns the first value of an array and array_last() the last one, by position, whatever the keys are. They read the array without changing it or its internal pointer, and since they take the array by value, you can pass a function result straight in. An empty array returns null, with no warning.

array_first.php
<?php

$fruits = ['apple', 'banana', 'cherry'];
echo array_first($fruits), ' ', array_last($fruits), "\n";

// Keys don't matter: associative arrays work the same way
$prices = ['tea' => 3, 'coffee' => 4, 'juice' => 5];
echo array_first($prices), ' ', array_last($prices), "\n";

// Nothing is removed and the internal pointer stays put
echo count($fruits), ' ', current($fruits), "\n";

// A function result can go straight in
echo array_last(explode('/', 'src/lib/util.php')), "\n";

// An empty array gives null
var_dump(array_first([]), array_last([]));

// So does a null element: check for [] when that matters
$values = [null, 'x'];
var_dump(array_first($values), $values === []);

Output

The list gives apple cherry and the associative array 3 5, the values of tea and juice. After both calls the array still has 3 elements and current() still points at apple. Passing explode()'s result directly gives util.php, which end() can't do cleanly (section 4). The empty array prints NULL twice, and [null, 'x'] prints NULL as well even though it isn't empty (the bool(false) from $values === []), so when null can be a real value, test $arr === [] first. Both functions accept only arrays: a generator throws a TypeError.

2array_key_first() and array_key_last() (PHP 7.3)

When you need the key, or your server runs a PHP older than 8.5, use array_key_first() and array_key_last(). They return the first and last key, or null for an empty array, and like the functions above they don't touch the internal pointer. Look the value up with the key, but only after checking for null: indexing with a null key is its own problem (see the note).

array_key_first.php
<?php

$scores = ['ana' => 91, 'ben' => 78, 'cy' => 85];

$firstKey = array_key_first($scores);
$lastKey = array_key_last($scores);
echo "$firstKey => {$scores[$firstKey]}\n";
echo "$lastKey => {$scores[$lastKey]}\n";

// Keys come in insertion order, not sorted order
$ids = [4 => 'x', 9 => 'y', 2 => 'z'];
var_dump(array_key_first($ids), array_key_last($ids));

// The value before PHP 8.5: check the key before using it
function firstValue(array $items): mixed
{
    $key = array_key_first($items);
    return $key === null ? null : $items[$key];
}

var_dump(firstValue($scores), firstValue([]));

Output

The first key is ana with 91 and the last is cy with 85. For [4 => 'x', 9 => 'y', 2 => 'z'] the keys are int(4) and int(2): the last key is the last one added, not the largest. firstValue([]) returns NULL quietly; on PHP 7.x, drop the mixed return type, which needs PHP 8.0. The one-liner $arr[array_key_first($arr)] is fine on a non-empty array, but on an empty one PHP 8.5 prints Deprecated: Using null as an array offset is deprecated, use an empty string instead and then Warning: Undefined array key "", so guard it as above.

3Why $arr[0] and count() - 1 go wrong

$arr[0] reads the element whose key is 0, not the first element, and $arr[count($arr) - 1] reads the key one less than the size. Those match only for a list numbered from 0 with no gaps. An associative array has no key 0, array_filter() keeps the original keys, and unset() leaves a gap. This example ends with a warning on purpose.

index_zero.php
<?php

// array_filter() keeps the original keys: here 1 and 3
$evens = array_filter([1, 2, 3, 4], fn(int $n): bool => $n % 2 === 0);
echo json_encode($evens), "\n";
var_dump($evens[0] ?? 'no key 0', array_first($evens));

// After unset() the size no longer points at the last key
$letters = ['a', 'b', 'c'];
unset($letters[0]);
echo $letters[count($letters) - 1], ' vs ', array_last($letters), "\n";

// An associative array has no key 0: a warning, then null
$scores = ['ana' => 91, 'ben' => 78, 'cy' => 85];
var_dump($scores[0]);

Output

json_encode shows the filtered array as {"1":2,"3":4}: the keys are 1 and 3, so $evens[0] ?? ... falls back to no key 0 while array_first() finds 2. The count() line is worse because nothing warns: it prints b vs c, a wrong answer that looks right. The last line prints NULL and, on stderr, Warning: Undefined array key 0 in /tmp/workspace/main.php on line 15. If you do want positions, array_values($arr)[0] renumbers a copy first, at the cost of copying the whole array.

4reset() and end(): the internal pointer

Before PHP 7.3 the standard answers were reset($arr) for the first value and end($arr) for the last. Both move the array's internal pointer and return the value it lands on, so key() right after gives that element's key. You will see them in a lot of existing code, and they have three catches: they change the pointer that current(), key() and next() use, they need a variable, and they return false for an empty array.

reset_end.php
<?php

$steps = ['first' => 'build', 'second' => 'test', 'third' => 'deploy'];

// end() moves the pointer to the last element and returns it
echo end($steps), "\n";
echo key($steps), "\n";

// reset() moves it back to the first element
echo reset($steps), "\n";
echo key($steps), "\n";

// Empty array: false, the same as a real false element
$empty = [];
$flags = [false, true];
var_dump(reset($empty), reset($flags));

// They take the array by reference, so store a result first
$parts = explode('/', 'src/lib/util.php');
echo end($parts), "\n";

Output

end() returns deploy and key() then gives third; reset() returns build and the key first. The empty array and [false, true] both print bool(false), so you can't tell them apart from the result alone. Passing a function result, as in end(explode(...)), still works but prints Notice: Only variables should be passed by reference, and a literal such as end([1, 2, 3]) is a fatal Error: end(): Argument #1 ($array) could not be passed by reference. That is why the last lines store the result in $parts first.

5array_slice(): first or last as an array

array_slice($arr, 0, 1) returns a one-element array holding the first element, and array_slice($arr, -1) one holding the last. It never fails on an empty array (you get []), it keeps string keys, and it is the function to reach for when you want the first or last few elements. Integer keys are renumbered unless you pass true as the fourth argument.

array_slice.php
<?php

$prices = ['tea' => 3, 'coffee' => 4, 'juice' => 5];

// One-element arrays; string keys are kept
echo json_encode(array_slice($prices, 0, 1)), "\n";
echo json_encode(array_slice($prices, -1)), "\n";

// Key and value of the last element in one go
foreach (array_slice($prices, -1) as $key => $value) {
    echo "$key costs $value\n";
}

// Integer keys are renumbered unless preserve_keys is true
$ids = [4 => 'x', 9 => 'y'];
echo json_encode(array_slice($ids, -1)), "\n";
echo json_encode(array_slice($ids, -1, 1, true)), "\n";

// The first or last N, and an empty array stays empty
echo json_encode(array_slice([1, 2, 3, 4, 5], 0, 3)), "\n";
echo json_encode(array_slice([1, 2, 3, 4, 5], -2)), "\n";
echo json_encode(array_slice([], -1)), "\n";

Output

json_encode prints an array with string keys as an object, so the first two lines read {"tea":3} and {"juice":5}. The loop prints juice costs 5, the last key and value together. For integer keys the default gives ["y"] (key 0), and preserve_keys keeps {"9":"y"}. The first three of five are [1,2,3], the last two [4,5], and an empty input gives []. To get the value itself you still need array_first() or a loop on the result, so for a single element the functions above are simpler.

6array_shift() and array_pop() remove the element

array_shift() and array_pop() also return the first and last value, but they take it out of the array. That is right for a queue or a stack and wrong when you only want to look. array_shift() also renumbers the integer keys that are left, so it changes more than one element.

shift_pop.php
<?php

$stack = ['a', 'b', 'c'];
$last = array_pop($stack);
echo $last, ' | left: ', json_encode($stack), "\n";

$queue = [3 => 'x', 7 => 'y', 'k' => 'z'];
$first = array_shift($queue);
echo $first, ' | left: ', json_encode($queue), "\n";

// To read without removing, use array_last() or array_first()
$stack = ['a', 'b', 'c'];
echo array_last($stack), ' | left: ', json_encode($stack), "\n";

// Empty array: null, no warning
$empty = [];
var_dump(array_pop($empty), array_shift($empty));

Output

array_pop() returns c and leaves ["a","b"]. array_shift() returns x, and the rest comes back as {"0":"y","k":"z"}: y moved from key 7 to key 0, while the string key k stayed. array_last() gives c and the array keeps all three. On an empty array both functions return NULL.

7Which should you use?

MethodEmpty arrayChanges the arrayBest for
array_first($a) / array_last($a)nullNoThe value, on PHP 8.5+
array_key_first($a) / array_key_last($a)nullNoThe key, or the value on PHP 7.3 to 8.4
reset($a) / end($a)falseMoves the pointerCode older than PHP 7.3
array_slice($a, 0, 1) / array_slice($a, -1)[]NoThe first or last N elements
array_shift($a) / array_pop($a)nullRemoves itQueues and stacks
$a[0] / $a[count($a) - 1]Warning, nullNoAvoid: wrong for keyed or gapped arrays

Frequently asked questions

How do I get the first element of an array in PHP?

On PHP 8.5, call array_first($arr). On PHP 7.3 to 8.4, use $arr === [] ? null : $arr[array_key_first($arr)]. Before 7.3, reset($arr) returns the first value and moves the internal pointer. All three work on associative arrays; $arr[0] does not.

What do array_first() and array_last() return for an empty array?

null, without a warning. They also return null when the element itself is null, so if that can happen, check $arr === [] or count($arr) first. reset() and end() return false instead, and array_slice() returns an empty array.

How do I get the last element of an array without removing it?

Use array_last($arr) on PHP 8.5, $arr[array_key_last($arr)] on PHP 7.3 to 8.4 (after checking the array is not empty), or end($arr) on older versions. array_pop() returns the last element too, but it removes it from the array.

How do I get the first or last key of an associative array?

array_key_first($arr) and array_key_last($arr), added in PHP 7.3. Both return null for an empty array and leave the internal pointer alone. In older code you will see reset($arr); $key = key($arr); or end($arr); $key = key($arr);.

Why does end() say "Only variables should be passed by reference"?

end() and reset() take the array by reference because they move its internal pointer, so they expect a variable. end(explode('/', $path)) still returns the last part but prints Notice: Only variables should be passed by reference, and end([1, 2, 3]) throws Error: end(): Argument #1 ($array) could not be passed by reference. Store the result in a variable first, or use array_last(), which takes its argument by value.

How do I get the first element of a generator or iterator?

array_first() accepts only arrays: a generator throws a TypeError with the message array_first(): Argument #1 ($array) must be of type array, Generator given. A generator has current() and key() for its first value and key. For the last one, convert it with iterator_to_array() and call array_last() on that.

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground