Get the first element of an array – Dev

The best answers to the question “Get the first element of an array” in the category Dev.


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?


As Mike pointed out (the easiest possible way):

$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
echo reset($arr); // Echoes "apple"

If you want to get the key: (execute it after reset)

echo key($arr); // Echoes "4"

From PHP’s documentation:

mixed reset ( array &$array );


reset() rewinds array’s internal pointer to the first element and returns the value of the first array element, or FALSE if the array is


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):




returns the first element of an array, according to the PHP manual.

Every array has an internal pointer to its “current” element, which is initialized to the first element inserted into the array.

So it works until you have re-positioned the array pointer, and otherwise you’ll have to use reset() which ll rewind array and ll return first element of array

According to the PHP manual reset.

reset() rewinds array’s internal pointer to the first element and returns the value of the first array element.

Examples of current() and reset()

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"

//Forward the array pointer and then reset it

// skip two steps
echo current($array) . "<br />\n"; // "step three"

// reset pointer, start again on step one
echo reset($array) . "<br />\n"; // "step one"


$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key