How to get the first element of an array in PHP without modifying the original array?
I have the following PHP array:
array(4 => 'apple', 7 => 'orange', 13 => 'plum')
I need to retrieve the first element (‘apple’) from this array. The expected result should be the string ‘apple’.
One important requirement: I cannot use functions that modify the original array by reference, so array_shift() is not an acceptable solution.
What is the best way to get the first element of an array in PHP without modifying the original array?
To get the first element of an array in PHP without modifying the original array, you can use array_key_first() combined with array indexing, which is the cleanest and most efficient approach. For your associative array array(4 => 'apple', 7 => 'orange', 13 => 'plum'), this would be:
$firstElement = $array[array_key_first($array)]; // Returns 'apple'
This approach preserves the original array completely and works with both indexed and associative arrays.
Contents
- Best Solutions
- Alternative Approaches
- Performance Comparison
- Future PHP 8.5 Solution
- Handling Edge Cases
Best Solutions
Using array_key_first() with Indexing
The recommended approach is to combine array_key_first() with direct array indexing:
$array = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
$firstElement = $array[array_key_first($array)];
echo $firstElement; // Outputs: 'apple'
Advantages:
- Doesn’t modify the original array in any way
- Works with both indexed and associative arrays
- Clean, readable syntax
- Available since PHP 7.3
This function specifically designed for this purpose and returns the first key of the array, which you can then use to access the corresponding value without affecting the original array structure.
array_values() with Indexing
Another clean approach is to use array_values() to get a new indexed array and access the first element:
$array = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
$firstElement = array_values($array)[0];
echo $firstElement; // Outputs: 'apple'
Note: While this approach works, it creates a new array copy which uses more memory for large arrays.
Alternative Approaches
Using reset() and current() with Pointer Restoration
If you’re comfortable temporarily modifying the internal pointer and restoring it:
$array = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
// Save current pointer position
$originalKey = key($array);
// Get first element
$firstElement = reset($array);
// Restore pointer to original position
if ($originalKey !== null) {
while (key($array) !== $originalKey) {
next($array);
}
}
echo $firstElement; // Outputs: 'apple'
Warning: This approach modifies the internal array pointer but doesn’t change the array structure itself. However, it’s more complex and error-prone.
Foreach Loop with Break
A simple but verbose approach:
$array = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
$firstElement = null;
foreach ($array as $value) {
$firstElement = $value;
break; // Exit after first iteration
}
echo $firstElement; // Outputs: 'apple'
Performance Comparison
| Method | Memory Usage | Speed | Modifies Array | Best For |
|---|---|---|---|---|
array_key_first() + indexing |
Low | Fast | No | General use |
array_values() + indexing |
High | Medium | No | Simple indexed arrays |
reset() + current() |
Low | Fast | Pointer only | Quick access |
| Foreach loop | Low | Slowest | No | Arrays with custom iteration needs |
According to performance benchmarks, array_key_first() + indexing is the most efficient method that doesn’t modify the original array structure.
Future PHP 8.5 Solution
PHP 8.5 introduces dedicated functions for this exact use case:
// Available in PHP 8.5+
$array = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
$firstElement = array_first($array);
echo $firstElement; // Outputs: 'apple'
As DevRiazul explains, these new functions solve the problem cleanly without side effects: “This is a classic example of a function with a side effect. While it gets the job done, it modifies the state of the array.”
Handling Edge Cases
Empty Arrays
If your array might be empty, always check first:
$array = []; // or null
$firstElement = null;
if (!empty($array)) {
$firstElement = $array[array_key_first($array)];
}
echo $firstElement; // Outputs: null
Single Element Arrays
Works the same way:
$array = array(42 => 'only');
$firstElement = $array[array_key_first($array)];
echo $firstElement; // Outputs: 'only'
Multidimensional Arrays
For nested arrays, use the same approach:
$array = array('fruits' => array(4 => 'apple', 7 => 'orange'));
$firstElement = $array['fruits'][array_key_first($array['fruits'])];
echo $firstElement; // Outputs: 'apple'
Sources
- How to get the First Element of an Array in PHP? - GeeksforGeeks
- How to Get the First Element of an Array in PHP | Delft Stack
- PHP 8.5 Introduces array_first() and array_last() - DevRiazul
- Understanding reset() and end() in PHP: Navigating Arrays Like a Pro
- New in PHP 8.5: array_first() and array_last() for Clean Array Access | Medium
Conclusion
The best way to get the first element of an array in PHP without modifying the original array is to use array_key_first() combined with array indexing. This approach is efficient, clean, and works with all types of arrays while preserving the original data structure intact.
For your specific example:
$array = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
$firstElement = $array[array_key_first($array)];
Key recommendations:
- Use
array_key_first() + indexingfor optimal performance - For PHP 8.5+, look forward to the dedicated
array_first()function - Always handle empty arrays with proper checks
- Avoid
array_shift()as it modifies the original array by reference
This solution meets all your requirements: it retrieves ‘apple’ from your array and keeps the original array completely unchanged.