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

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

    You can make:

    $values = array_values($array);
    echo $values[0];
    
    0 讨论(0)
  • 2021-01-31 01:26

    There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.

    $first = array_shift($array);
    

    current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.

    $first = current($array);
    

    If you want to make sure that it is pointing to the first element, you can always use reset().

    reset($array);
    $first = current($array);
    
    0 讨论(0)
  • 2021-01-31 01:36

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

    Instead of

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

    As reset()

    returns the first element of the array after reset;

    0 讨论(0)
提交回复
热议问题