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

后端 未结 15 2020
温柔的废话
温柔的废话 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

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

提交回复
热议问题