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

后端 未结 15 2062
温柔的废话
温柔的废话 2021-01-31 00:33

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

15条回答
  •  天涯浪人
    2021-01-31 01:14

    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)];
    

提交回复
热议问题