Aren't current() and end() good enough?
During one of my one-on-one consultations, a reader and I were discussing an article about what's new in PHP 8.5, in particular the new array_first() and array_last() functions.
He asked:
“Why do we need them if we have current() and end()?”
And it suddenly occurred to me that he might not be the only one with this question, because it may seem that current() and end() do the same thing.
So I decided to briefly lay it all out.
What current() and end() actually do
current() does return the first element and end() the last element of an array, but only until the array's internal pointer moves. This means that:
$array = ['a', 'b', 'c', 'd'];
echo current($array); // 'a'
echo next($array); // 'b'
echo current($array); // 'b', not 'a'
echo end($array); // 'd'
echo current($array); // 'd', not 'a'
In other words, current() returns not the first element of the array but the one the pointer points to, and end() returns the last element but also moves the array's internal pointer to it, which in turn can lead to unpredictable consequences.
A conceptual example: we want to print all elements of the array if the last element is not "d".
$array = ['a', 'b', 'c'];
if (end($array) !== 'd') { // but the pointer has already moved to 'c'
while ($item = current($array)) {
echo $item . PHP_EOL;
next($array);
}
}
But only 'c' will be printed.
array_first() and array_last() — declarative and predictable
The new functions will always return the first or the last value without side effects.
They don't change the state of the pointer and don't depend on it:
$array = ['a', 'b', 'c'];
array_first($array); // 'a'
array_last($array); // 'c'
// Regardless of the pointer
next($array);
array_first($array); // still 'a'
PHP keeps evolving towards declarative and safe code, and these new functions are not "extra" — they are one more step towards fewer bugs.
If you notice current() or end() in your code, maybe it's time to look at them from a new angle.
First published in Ukrainian in the Telegram channel “Created to die” on June 25, 2025.