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?
Original answer, but costly (O(n)):
array_shift(array_values($array));
In O(1):
array_pop(array_reverse($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+ (but might cause an index error if empty):
array_values($array)[0];
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 );
Description:
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 empty.
$first_value = reset($array); // First Element's Value
$first_key = key($array); // First Element's Key
Hope this helps. :)
链接地址: http://www.djcxy.com/p/18584.html上一篇: 我在哪里可以找到表格格式的时区列表?
下一篇: 获取数组的第一个元素