Php – Get the first element of an array


I have an array:

array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )

I would like to get the first element of this array. Expected result: string apple

One requirement: it cannot be done with passing by reference, so array_shift is not a good solution.

How can I do this?

Best Solution

Original answer, but costly (O(n)):


In O(1):


Other use cases, etc...

If modifying (in the sense of resetting array pointers) of $array is not a problem, you might use:


This should be theoretically more efficient, if a array "copy" is needed:

array_shift(array_slice($array, 0, 1));

With PHP 5.4+ (but might cause an index error if empty):