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

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

    Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:

    $arr = array(1,2);
    current($arr); // 1
    next($arr);    // 2
    current($arr); // 2
    reset($arr);   // 1
    current($arr); // 1 !This was 2 before! We've changed the array's pointer.
    

    The way to do this without changing the pointer:

    $arr[reset(array_keys($arr))]; // OR
    reset(array_values($arr));
    

    The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.

提交回复
热议问题