Back to Publication
PHP
By Riazul Islam•
Summary: PHP 8.5 brings two handy new built-in functions - array_first() and array_last() - simplifying how developers access array elements.
## Introduction
PHP 8.5 introduces two simple yet incredibly useful functions: **`array_first()`** and **`array_last()`**. These functions solve a common pain point that PHP developers have faced for years - safely accessing the first and last elements of an array.
---
## The Problem Before PHP 8.5
Before these functions, developers had to use workarounds:
```php
// Method 1: reset() - modifies internal pointer (side effect!)
$first = reset($array);
// Method 2: array_key_first + access
$first = $array[array_key_first($array)] ?? null;
// Method 3: array_values + index
$first = array_values($array)[0] ?? null;
// For last element:
$last = end($array); // Also modifies internal pointer!
$last = $array[array_key_last($array)] ?? null;
```
Each approach had drawbacks - side effects, verbosity, or poor readability.
---
## The New Solution
### `array_first()`
Returns the first element of an array without modifying the internal pointer:
```php
$fruits = ['apple', 'banana', 'cherry'];
$first = array_first($fruits);
// Result: 'apple'
// Works with associative arrays too
$user = ['name' => 'Riazul', 'role' => 'Developer', 'city' => 'Dhaka'];
$first = array_first($user);
// Result: 'Riazul'
```
### `array_last()`
Returns the last element of an array:
```php
$fruits = ['apple', 'banana', 'cherry'];
$last = array_last($fruits);
// Result: 'cherry'
$scores = [85, 92, 78, 95];
$latest = array_last($scores);
// Result: 95
```
---
## Handling Empty Arrays
Both functions return `null` for empty arrays - no errors, no warnings:
```php
$empty = [];
$first = array_first($empty); // null
$last = array_last($empty); // null
```
---
## No Side Effects
Unlike `reset()` and `end()`, these functions do **not** modify the array's internal pointer:
```php
$array = [1, 2, 3, 4, 5];
// Internal pointer stays at current position
next($array); // pointer at 2
next($array); // pointer at 3
$first = array_first($array); // 1
$current = current($array); // Still 3! Not modified.
```
---
## Real-World Use Cases
### Getting the Latest Record
```php
$orders = Order::latest()->get()->toArray();
$latestOrder = array_last($orders);
```
### Default Configuration Values
```php
$configs = loadConfigurations();
$primaryConfig = array_first($configs);
```
### Queue Processing
```php
$queue = getQueuedJobs();
$nextJob = array_first($queue);
if ($nextJob) {
processJob($nextJob);
}
```
### Breadcrumb Navigation
```php
$breadcrumbs = ['Home', 'Products', 'Electronics', 'Laptops'];
$currentPage = array_last($breadcrumbs); // 'Laptops'
```
---
## Performance
Both functions are implemented in C at the engine level, making them:
- **Faster** than userland implementations
- **Memory efficient** - no array copying
- **O(1) complexity** for indexed arrays
---
## Comparison Table
| Approach | Side Effects | Null-Safe | Readable |
| `reset()` / `end()` | ✅ Yes | ❌ No | ⚠️ Fair |
| `array_key_first/last` | ❌ No | ⚠️ Partial | ❌ Poor |
| `array_values()[0]` | ❌ No | ❌ No | ⚠️ Fair |
| **`array_first/last()`** | **❌ No** | **✅ Yes** | **✅ Excellent** |
---
## Conclusion
`array_first()` and `array_last()` are exactly the kind of quality-of-life improvements that make PHP a better language with each release. They're simple, intuitive, side-effect-free, and handle edge cases gracefully. Start using them as soon as you upgrade to PHP 8.5!
