Get the first element of an array

后端 未结 30 2383
醉酒成梦
醉酒成梦 2020-11-22 10:59

I have an array:

array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' )

I would like to get the first element of this array. Expect

30条回答
  •  攒了一身酷
    2020-11-22 11:23

    Some arrays don't work with functions like list, reset or current. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.

    If you want to pull the first value regardless of the array, you can short-circuit an iterator:

    foreach($array_with_unknown_keys as $value) break;
    

    Your value will then be available in $value and the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).

    You can grab the key this way too:

    foreach($array_with_unknown_keys as $key=>$value) break;
    

    If you're calling this from a function, simply return early:

    function grab_first($arr) {
        foreach($arr as $value) return $value;
    }
    

提交回复
热议问题