得到的阵列的第一个元素 [英] Get the first element of an array

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

问题描述

我有一个数组:

阵列(4 =>'苹果',7 =>橙色,13 =>'梅花')

我想获得这个数组的第一个元素。预期结果:字符串 苹果

一个要求:不能用引用传递完成的,所以 array_shift 不是一个很好的解决方案。

我怎样才能做到这一点?


解决方案

  array_shift(array_values​​($阵列));

搭配建议编辑从其他用例的意见等等......

如果修改(重置中与数组指针的意义上) $阵列是没有问题的,你可以使用:

 复位($数组);

这应该是理论上更有效率,如果需要阵副本:

  array_shift(array_slice($数组,0,1));

使用PHP 5.4 +

  array_values​​($数组)[0];

来自匿名用户的注意事项(未验证):
如果你只是想通过在整体数组,preFER使用 array_pop(),因为 array_shift 为O(n)的复杂性,而 array_pop 有O(1)。

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?

解决方案

array_shift(array_values($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+:

array_values($array)[0]; 

A note from an anonymous user (unverified): If you only want to go through the array in totality, prefer the use of array_pop(), because array_shift has O(n) complexity, whereas array_pop has O(1).

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

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