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?
Two solutions for you.
Solution 1 - Just use the key. You have not said, that you can not use it. :)
Solution 2 - array_flip() + key()
Solution 3 - array_keys()
As Mike pointed out (the easiest possible way):
If you want to get the key: (execute it after reset)
From PHP's documentation:
Description:
PHP 5.4+:
You can get Nth element with a language construct "list":
with array_keys function you can do the same for keys:
From Laravel's helpers:
The array being passed by value to the function, the reset() affects the internal pointer of a copy of the array, it doesn't touch the original array. (note it returns
false
if the array is empty)Usage example:
Also, here is an alternative. It's very marginally faster, but more interesting, it lets easily change the default value if the array is empty:
Keep this simple! Lots of correct answers here, but to minimize all the confusion. These two work and reduce a lot of overhead.
key($array)
= gets the first key of an arraycurrent($array)
= gets the first value of an array