Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

php - 获取数组的第一个元素(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 预期结果: apple) One requirement: it cannot be done with passing by reference , so array_shift is not a good solution. (一个要求: 它不能通过引用传递来完成 ,所以array_shift不是一个好的解决方案。) How can I do this? (我怎样才能做到这一点?)   ask by hsz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(原始答案,但代价昂贵(O(n)):)

array_shift(array_values($array));

In O(1):

(在O(1)中:)

array_pop(array_reverse($array));

Other use cases, etc...

(其他用例等)

If modifying (in the sense of resetting array pointers) of $array is not a problem, you might use:

(如果修改(在复位数组指针的意义上) $array不是问题,则可以使用:)

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

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

array_values($array)[0];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...