Get the first element of an array

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

    As Mike pointed out (the easiest possible way):

    $arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
    echo reset($arr); // Echoes "apple"
    

    If you want to get the key: (execute it after reset)

    echo key($arr); // Echoes "4"
    

    From PHP's documentation:

    mixed reset ( array &$array );

    Description:

    reset() rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.

提交回复
热议问题