获取数组的第一个元素 [英] Get the first element of an array

查看:61
本文介绍了获取数组的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )

我想得到这个数组的第一个元素.预期结果:string apple

I would like to get the first element of this array. Expected result: string apple

一个要求:不能通过引用传递,所以array_shift不是一个好的解决方案.

One requirement: it cannot be done with passing by reference, so array_shift is not a good solution.

我该怎么做?

推荐答案

原始答案,但成本高 (O(n)):

Original answer, but costly (O(n)):

array_shift(array_values($array));

在 O(1) 中:

array_pop(array_reverse($array));

其他用例等...

如果修改(在重置数组指针的意义上)$array 没有问题,您可以使用:

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));

使用 PHP 5.4+(但如果为空可能会导致索引错误):

With PHP 5.4+ (but might cause an index error if empty):

array_values($array)[0];

这篇关于获取数组的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆