β Aren't current() and end() good enough?
docs: English JsonRpcBundle docs, REST and MCP Bundle sections, package cards
en/articles/from-tg/php/array-first-last.md
new file +69
β0
1
+
# Aren't current() and end() good enough?
2
+
3
+
During one of my one-on-one consultations, a reader and I were discussing [an article about what's new in PHP 8.5](https://sensiolabs.com/blog/2025/new-in-php-85), in particular the new `array_first()` and `array_last()` functions.
4
+
5
+
He asked:
6
+
7
+
> βWhy do we need them if we have current() and end()?β
8
+
9
+
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.
10
+
11
+
So I decided to briefly lay it all out.
12
+
13
+
## What current() and end() actually do
14
+
15
+
`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:
16
+
17
+
```php
18
+
$array = ['a', 'b', 'c', 'd'];
19
+
20
+
echo current($array); // 'a'
21
+
22
+
echo next($array); // 'b'
23
+
echo current($array); // 'b', not 'a'
24
+
25
+
echo end($array); // 'd'
26
+
echo current($array); // 'd', not 'a'
27
+
```
28
+
29
+
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.
30
+
31
+
A conceptual example: we want to print all elements of the array if the last element is not "d".
32
+
33
+
```php
34
+
$array = ['a', 'b', 'c'];
35
+
36
+
if (end($array) !== 'd') { // but the pointer has already moved to 'c'
37
+
while ($item = current($array)) {
38
+
echo $item . PHP_EOL;
39
+
next($array);
40
+
}
41
+
}
42
+
```
43
+
44
+
But only 'c' will be printed.
45
+
46
+
## array_first() and array_last() β declarative and predictable
47
+
48
+
The new functions will always return the first or the last value without side effects.
49
+
50
+
They don't change the state of the pointer and don't depend on it:
51
+
52
+
```php
53
+
$array = ['a', 'b', 'c'];
54
+
55
+
array_first($array); // 'a'
56
+
array_last($array); // 'c'
57
+
58
+
// Regardless of the pointer
59
+
next($array);
60
+
array_first($array); // still 'a'
61
+
```
62
+
63
+
PHP keeps evolving towards declarative and safe code, and these new functions are not "extra" β they are one more step towards fewer bugs.
64
+
65
+
If you notice `current()` or `end()` in your code, maybe it's time to look at them from a new angle.
66
+
67
+
---
68
+
69
+
*First published in Ukrainian in the Telegram channel [βCreated to dieβ](https://t.me/php_while_true/44) on June 25, 2025.*