Get first key in a (possibly) associative array?

2019-01-01 08:05发布

What's the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this:

foreach ($an_array as $key => $val) break;

Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?

标签: php arrays
19条回答
牵手、夕阳
2楼-- · 2019-01-01 08:27

Please find the following:

$yourArray = array('first_key'=> 'First', 2, 3, 4, 5);
$keys   =   array_keys($yourArray);
echo "Key = ".$keys[0];

I think this will work.

查看更多
旧人旧事旧时光
3楼-- · 2019-01-01 08:30

php73:

$array = ['a' => '..', 'b' => '..'];

array_key_first($array); // 'a'
array_key_last($array); // 'b';

http://php.net/manual/en/function.array-key-first.php

查看更多
流年柔荑漫光年
4楼-- · 2019-01-01 08:31

You can play with your array

$daysArray = array('Monday', 'Tuesday', 'Sunday');
$day = current($transport); // $day = 'Monday';
$day = next($transport);    // $day = 'Tuesday';
$day = current($transport); // $day = 'Tuesday';
$day = prev($transport);    // $day = 'Monday';
$day = end($transport);     // $day = 'Sunday';
$day = current($transport); // $day = 'Sunday';

To get the first element of array you can use current and for last element you can use end

Edit

Just for the sake for not getting any more down votes for the answer you can convert you key to value using array_keys and use as shown above.

查看更多
浮光初槿花落
5楼-- · 2019-01-01 08:32

Today I had to search for the first key of my array returned by a POST request. (And note the number for a form id etc)

Well, I've found this: Return first key of associative array in PHP

http://php.net/key

I've done this, and it work.

    $data = $request->request->all();
    dump($data);
    while ($test = current($data)) {
        dump($test);
        echo key($data).'<br />';die();
        break;
    }

Maybe it will eco 15min of an other guy. CYA.

查看更多
像晚风撩人
6楼-- · 2019-01-01 08:34

A one-liner:

$array = array('key1'=>'value1','key2'=>'value2','key3'=>'key3');
echo key( array_slice( $array, 0, 1, true ) );

# echos 'key1'
查看更多
余生无你
7楼-- · 2019-01-01 08:37
list($firstKey) = array_keys($yourArray);
查看更多
登录 后发表回答