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?
Solution :
array_shift(array_values($array));
Edited with suggestions from comments for other use cases etc...
If modifying (in the sense of resetting array pointers) of
$array
is not a problem, you might use:reset($array);
This should be theoretically more efficient, if a array "copy" is needed:
array_shift(array_slice($array, 0, 1));
With PHP 5.4+:
array_values($array)[0];
A note from an anonymous user (unverified): If you only want to go through the array in totality, prefer the use of array_pop(), because array_shift has O(n) complexity, whereas
array_pop
has O(1).
http://stackoverflow.com/questions/1921421/get-the-first-element-of-an-array
COMMENTS