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

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

    Use reset() function to get the first item out of that array without knowing the key for it like this.

    $value = array('foo' => 400, 'bar' => 'xyz');
    echo reset($value);

    output // 400

    0 讨论(0)
  • 2021-01-31 01:13

    another easy and simple way to do it use array_values

    array_values($array)[0]
    
    0 讨论(0)
  • 2021-01-31 01:14

    Fake loop that breaks on the first iteration:

    $key = $value = NULL;
    foreach ($array as $key => $value) {
        break;
    }
    
    echo "$key = $value\n";
    

    Or use each() (warning: deprecated as of PHP 7.2.0):

    reset($array);
    list($key, $value) = each($array);
    
    echo "$key = $value\n";
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 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)];
    
    0 讨论(0)
  • 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.

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