我有一个数组:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
我想得到这个数组的第一个元素。结果预计是: string apple
一个问题是:它不能通过引用传递,所以数组移位不是一个好的解决方案。
可以怎么做?
我有一个数组:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
我想得到这个数组的第一个元素。结果预计是: string apple
一个问题是:它不能通过引用传递,所以数组移位不是一个好的解决方案。
可以怎么做?
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];