Return first key of associative array in PHP

前端 未结 5 1761
日久生厌
日久生厌 2020-12-13 06:24

I\'m trying to obtain the first key of an associative array, without creating a temporary variable via array_keys() or the like, to pass by reference. Unfortuna

相关标签:
5条回答
  • 2020-12-13 06:44

    each() still a temporary required, but potentially a much smaller overhead than using array_keys().

    0 讨论(0)
  • 2020-12-13 06:47

    What about using array_slice (in combination with array_keys for associative arrays)?

    $a = range(0,999999);
    var_dump(memory_get_peak_usage());
    $k = array_keys(array_slice($a, 0, 1, TRUE))[0];
    var_dump(memory_get_peak_usage());
    var_dump($k);
    $k = array_keys($a)[0];
    var_dump(memory_get_peak_usage());
    

    Gives as output (at least with me):

    int(36354360)
    int(36355112)
    int(0)
    int(72006024)
    int(0)
    
    0 讨论(0)
  • 2020-12-13 06:54

    Although array_shift(array_keys($array)); will work, current(array_keys($array)); is faster as it doesn't advance the internal pointer.

    Either one will work though.

    Update

    As @TomcatExodus noted, array_shift(); expects an array passed by reference, so the first example will issue an error. Best to stick with current();

    0 讨论(0)
  • 2020-12-13 07:09
    array_shift(array_keys($array))
    
    0 讨论(0)
  • 2020-12-13 07:11

    You can use reset and key:

    reset( $array );
    $first_key = key( $array );
    

    or, you can use a function:

    function firstIndex($a) { foreach ($a as $k => $v) return $k; }
    $key = firstIndex( $array );
    
    0 讨论(0)
提交回复
热议问题