NeuroAgent

Get First Element of Array in PHP Without Modifying

Learn the best methods to get the first element of an array in PHP without modifying the original array. Discover efficient solutions using array_key_first() and other approaches.

Question

How to get the first element of an array in PHP without modifying the original array?

I have the following PHP array:

php
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?

NeuroAgent

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:

php
$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

Using array_key_first() with Indexing

The recommended approach is to combine array_key_first() with direct array indexing:

php
$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:

php
$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:

php
$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:

php
$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:

php
// 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:

php
$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:

php
$array = array(42 => 'only');
$firstElement = $array[array_key_first($array)];
echo $firstElement; // Outputs: 'only'

Multidimensional Arrays

For nested arrays, use the same approach:

php
$array = array('fruits' => array(4 => 'apple', 7 => 'orange'));
$firstElement = $array['fruits'][array_key_first($array['fruits'])];
echo $firstElement; // Outputs: 'apple'

Sources

  1. How to get the First Element of an Array in PHP? - GeeksforGeeks
  2. How to Get the First Element of an Array in PHP | Delft Stack
  3. PHP 8.5 Introduces array_first() and array_last() - DevRiazul
  4. Understanding reset() and end() in PHP: Navigating Arrays Like a Pro
  5. 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:

php
$array = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
$firstElement = $array[array_key_first($array)];

Key recommendations:

  • Use array_key_first() + indexing for 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.