php 获取数组的第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1921421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:19:00  来源:igfitidea点击:

Get the first element of an array

phparrays

提问by hsz

I have an array:

我有一个数组:

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

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

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

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

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

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

How can I do this?

我怎样才能做到这一点?

回答by blueyed

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 $arrayis 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];

回答by lepe

As Mike pointed out (the easiest possible way):

正如迈克指出的那样(最简单的方法):

$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
echo reset($arr); // Echoes "apple"

If you want to get the key: (execute it after reset)

如果要获取密钥:(重置后执行)

echo key($arr); // Echoes "4"

From PHP's documentation:

来自PHP 的文档

mixedreset( array &$array);

混合重置(数组&$array);

Description:

描述:

reset()rewinds array'sinternal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.

reset() 将数组的内部指针倒回到第一个元素并返回第一个数组元素的值,如果数组为空,则返回 FALSE。

回答by Ijas Ameenudeen

$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key

回答by yoda

$arr = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // echoes 'apple'

If you don't want to lose the current pointer position, just create an alias for the array.

如果不想丢失当前的指针位置,只需为数组创建一个别名。

回答by Tofeeq

current($array)can get you the first element of an array, according to the PHP manual.

current($array)根据 PHP 手册,可以为您获取数组的第一个元素。

Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.

每个数组都有一个指向其“当前”元素的内部指针,该指针被初始化为插入到数组中的第一个元素。

So it works until you have re-positioned the array pointer, and otherwise you'll have to reset the array.

所以它会一直工作,直到您重新定位数组指针,否则您将不得不重置数组。

回答by Sergiy Sokolenko

You can get the Nth element with a language construct, "list":

您可以使用语言结构“列表”获取第 N 个元素:

// First item
list($firstItem) = $yourArray;

// First item from an array that is returned from a function
list($firstItem) = functionThatReturnsArray();

// Second item
list( , $secondItem) = $yourArray;

With the array_keysfunction you can do the same for keys:

使用该array_keys功能,您可以对键执行相同操作:

list($firstKey) = array_keys($yourArray);
list(, $secondKey) = array_keys($yourArray);

回答by Samer Ata

PHP 5.4+:

PHP 5.4+:

array_values($array)[0];

回答by Alex Shesterov

PHP 7.3added two functions for getting the first and the last key of an array directlywithout modification of the original array and without creating any temporary objects:

PHP 7.3增加了两个函数,用于直接获取数组的第一个和最后一个键,无需修改原始数组,也无需创建任何临时对象:

Apart from being semantically meaningful, these functions don't even move the array pointer (as foreachwould do).

除了在语义上有意义之外,这些函数甚至不移动数组指针(就像foreach会做的那样)。

Having the keys, one can get the values by the keys directly.

有了键,就可以直接通过键获取值。



Examples (all of them require PHP 7.3+)

示例(所有这些都需要 PHP 7.3+)

Getting the first/last key and value:

获取第一个/最后一个键和值:

$my_array = ['IT', 'rules', 'the', 'world'];

$first_key = array_key_first($my_array);
$first_value = $my_array[$first_key];

$last_key = array_key_last($my_array);
$last_value = $my_array[$last_key];

Getting the first/last value as one-liners, assuming the array cannot be empty:

假设数组不能为空,将第一个/最后一个值作为单行获取:

$first_value = $my_array[ array_key_first($my_array) ];

$last_value = $my_array[ array_key_last($my_array) ];

Getting the first/last value as one-liners, with defaults for empty arrays:

将第一个/最后一个值作为单行获取,默认为空数组:

$first_value = empty($my_array) ? 'default' : $my_array[ array_key_first($my_array) ];

$last_value = empty($my_array) ? 'default' : $my_array[ array_key_last($my_array) ];

回答by Lucas

Suppose:

认为:

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

Just use:

只需使用:

$array[key($array)]

to get first element or

获取第一个元素或

key($array)

to get first key.

获得第一把钥匙。

Or you can unlink the first if you want to remove it.

或者,如果您想删除它,您可以取消链接第一个。

回答by Lee Benson

Some arrays don't work with functions like list, resetor current. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.

某些数组不适用于list,reset或等函数current。也许它们是“人造”数组——例如,部分实现了 ArrayIterator。

If you want to pull the first value regardless of the array, you can short-circuit an iterator:

如果你想拉第一个值而不考虑数组,你可以短路迭代器:

foreach($array_with_unknown_keys as $value) break;

Your value will then be available in $valueand the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).

然后您的值将可用,$value循环将在第一次迭代后中断。这比将一个潜在的大数组复制到像 array_unshift(array_values($arr)) 这样的函数更有效。

You can grab the key this way too:

您也可以通过这种方式获取密钥:

foreach($array_with_unknown_keys as $key=>$value) break;

If you're calling this from a function, simply return early:

如果您从函数中调用它,只需提前返回:

function grab_first($arr) {
    foreach($arr as $value) return $value;
}