How to get the first item from an associative PHP

2020-05-16 13:27发布

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?

标签: php
15条回答
我只想做你的唯一
2楼-- · 2020-05-16 13:53

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));
?>
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-05-16 13:55

Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:

$first = $array[array_key_first($array)];

More likely, you'll want to handle the case where the array is empty:

$first = (empty($array)) ? $default : $array[array_key_first($array)];
查看更多
祖国的老花朵
4楼-- · 2020-05-16 13:56

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.

For Example:

if(is_array($array))
{
  reset($array);
  $first = key($array);
}
查看更多
聊天终结者
5楼-- · 2020-05-16 13:56

Use reset() function to get the first item out of that array without knowing the key for it like this.

$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);

output // 400

查看更多
霸刀☆藐视天下
6楼-- · 2020-05-16 13:57

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

Instead of

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

As reset()

returns the first element of the array after reset;

查看更多
迷人小祖宗
7楼-- · 2020-05-16 13:58

another easy and simple way to do it use array_values

array_values($array)[0]
查看更多
登录 后发表回答