
我有一个数组:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
我想获得这个数组的第一个元素。预期结果:字符串apple
一个要求:通过引用不能完成,所以array_shift不是一个好的解决方案。
我怎样才能做到这一点?
原始答案,但昂贵(O(n)):
array_shift(array_values($array));
在O(1)中:
array_pop(array_reverse($array));
其他使用案例的意见建议编辑…
如果修改$array(在重置数组指针的意义上)不是问题,那么可以使用:
reset($array);
如果需要数组“复制”,这应该在理论上更有效率:
array_shift(array_slice($array, 0, 1));
使用PHP 5.4+(但如果为空,可能会导致索引错误):
array_values($array)[0];
正如Mike指出的那样(最简单的方法):
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
echo reset($arr); //echoes "apple"
如果你想获得钥匙:(复位后执行)
echo key($arr); //echoes "4"
从PHP的文档:
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 empty.
未经作者同意,本文严禁转载,违者必究!




近期评论