Get the first element of an array

后端 未结 30 2385
醉酒成梦
醉酒成梦 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:40

    Original answer, but costly (O(n)):

    array_shift(array_values($array));
    

    In O(1):

    array_pop(array_reverse($array));
    

    Other use cases, etc...

    If modifying (in the sense of resetting array pointers) of $array is not a problem, you might use:

    reset($array);
    

    This should be theoretically more efficient, if a array "copy" is needed:

    array_shift(array_slice($array, 0, 1));
    

    With PHP 5.4+ (but might cause an index error if empty):

    array_values($array)[0];
    

提交回复
热议问题