如何从关联的 PHP 数组中获取第一项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1617157/
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 03:16:55  来源:igfitidea点击:

How to get the first item from an associative PHP array?

php

提问by Click Upvote

If I had an array like:

如果我有一个像这样的数组:

$array['foo'] = 400;
$array['bar'] = 'xyz';

And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?

我想在不知道它的键的情况下从该数组中取出第一项,我该怎么做?有这个功能吗?

回答by soulmerge

reset()gives you the first value of the array if you have an element inside the array:

reset()如果数组中有元素,则为您提供数组的第一个值:

$value = reset($array);

It also gives you FALSEin case the array is empty.

FALSE如果数组为空,它也会为您提供。

回答by LSerni

PHP < 7.3

PHP < 7.3

If you don't know enough about the array (you're not sure whether the first key is fooor bar) then the array might well also be, maybe, empty.

如果您对数组不够了解(您不确定第一个键是foo还是bar),那么该数组也可能是,也许是empty

So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:

所以最好检查一下,特别是如果返回值可能是布尔值 FALSE:

$value = empty($arr) ? $default : reset($arr);

The above code uses resetand so has side effects(it resets the internal pointer of the array), so you might prefer using array_sliceto quickly access a copy of the first element of the array:

上面的代码使用reset有副作用(它重置数组的内部指针),因此您可能更喜欢使用array_slice快速访问数组第一个元素的副本:

$value = $default;
foreach(array_slice($arr, 0, 1) as $value);


Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:

假设要分别获取键和值,则需要将第四个参数添加到array_slice

foreach(array_slice($arr, 0, 1, true) as $key => $value);

To get the first item as a pair(key => value):

将第一项作为对( key => value) 获取:

$item = array_slice($arr, 0, 1, true);

Simple modification to get the lastitem, key and value separately:

简单修改,分别获取最后一项,key和value:

foreach(array_slice($arr, -1, 1, true) as $key => $value);

performance

表现

If the array is not really big, you don't actually need array_sliceand can rather get a copy of the whole keys array, then get the first item:

如果数组不是很大,您实际上并不需要array_slice,而是可以获取整个键数组的副本,然后获取第一项:

$key = count($arr) ? array_keys($arr)[0] : null;

If you have a very big array, though, the call to array_keyswill require significant time and memory more than array_slice(both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).

但是,如果您有一个非常大的数组,则调用array_keys将需要大量的时间和内存array_slice(两个函数都遍历数组,但后者在收集到所需数量的项目后立即终止 - 这是一个)。

A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slicewill duplicate that first large object, while array_keyswill only grab the keys.

一个值得注意的例外是当您拥有指向一个非常大且复杂的对象的第一个键时。在这种情况下,array_slice将复制第一个大对象,而array_keys只会抓取钥匙。

PHP 7.3

PHP 7.3

PHP 7.3 implements array_key_first()as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.

PHP 7.3 实现array_key_first()以及array_key_last(). 这些是明确提供的,以有效地访问第一个和最后一个键,而不会重置数组的内部状态作为副作用。

So in PHP 7.3 the first valueof $arraymay be accessed with

因此,在PHP 7.3的第一个$array可访问

$array[array_key_first($array)];

You still had better check that the array is not empty though, or you will get an error:

你还是最好检查一下数组是否为空,否则你会得到一个错误:

$firstKey = array_key_first($array);
if (null === $firstKey) {
    $value = "Array is empty"; // An error should be handled here
} else {
    $value = $array[$firstKey];
}

回答by John Kugelman

Fake loop that breaks on the first iteration:

在第一次迭代时中断的假循环:

$key = $value = NULL;
foreach ($array as $key => $value) {
    break;
}

echo "$key = $value\n";

Or use each()(warning:deprecated as of PHP 7.2.0):

或使用each()警告:自 PHP 7.2.0 起已弃用):

reset($array);
list($key, $value) = each($array);

echo "$key = $value\n";

回答by Jeremy Ruten

There's a few options. array_shift()will return the first element, but it will also remove the first element from the array.

有几个选项。array_shift()将返回第一个元素,但它也会从数组中删除第一个元素。

$first = array_shift($array);

current()will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.

current()将返回其内部内存指针指向的数组的值,默认为第一个元素。

$first = current($array);

If you want to make sure that it is pointing to the first element, you can always use reset().

如果你想确保它指向第一个元素,你总是可以使用reset().

reset($array);
$first = current($array);

回答by cwallenpoole

Just so that we have some other options: reset($arr);good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:

只是为了让我们有一些其他选择:reset($arr);如果您不试图将数组指针保持在适当的位置就足够了,并且对于非常大的数组,它会产生最小的开销。也就是说,它存在一些问题:

$arr = array(1,2);
current($arr); // 1
next($arr);    // 2
current($arr); // 2
reset($arr);   // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.

The way to do this without changing the pointer:

在不更改指针的情况下执行此操作的方法:

$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));

The benefit of $arr[reset(array_keys($arr))];is that it raises an warning if the array is actually empty.

的好处$arr[reset(array_keys($arr))];是,如果数组实际上是空的,它会发出警告。

回答by Beginner

another easy and simple way to do it use array_values

另一种简单易行的方法是使用 array_values

array_values($array)[0]

回答by w3bMak3r

Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.

在获取第一个元素之前测试 a 变量是否为数组。当动态创建数组时,如果它被设置为 null,你会得到一个错误。

For Example:

例如:

if(is_array($array))
{
  reset($array);
  $first = key($array);
}

回答by Suryasish Dey

We can do $first = reset($array);

我们可以做的 $first = reset($array);

Instead of

代替

reset($array);
$first = current($array);

As reset()

作为 reset()

returns the first element of the array after reset;

重置后返回数组的第一个元素;

回答by Walk

You can try this.

你可以试试这个。

To get first value of the array :-

获取数组的第一个值:-

<?php
   $large_array = array('foo' => 'bar', 'hello' => 'world');
   var_dump(current($large_array));
?>

To get the first key of the array

获取数组的第一个键

<?php
   $large_array = array('foo' => 'bar', 'hello' => 'world');
   $large_array_keys = array_keys($large_array);
   var_dump(array_shift($large_array_keys));
?>

回答by d0niek

You can make:

你(们)能做到:

$values = array_values($array);
echo $values[0];