Return first key of associative array in PHP

前端 未结 5 1766
日久生厌
日久生厌 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: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)
    

提交回复
热议问题