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 14:00

You can make:

$values = array_values($array);
echo $values[0];
查看更多
家丑人穷心不美
3楼-- · 2020-05-16 14:04

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

$value = reset($array);

It also gives you FALSE in case the array is empty.

查看更多
小情绪 Triste *
4楼-- · 2020-05-16 14:04

I do this to get the first and last value. This works with more values too.

$a = array(
    'foo' => 400,
    'bar' => 'xyz',
);
$first = current($a);   //400
$last = end($a);    //xyz
查看更多
登录 后发表回答