Get the first element of an array

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

    Use array_keys() to access the keys of your associative array as a numerical indexed array, which is then again can be used as key for the array.

    When the solution is arr[0]:

    (Note, that since the array with the keys is 0-based index, the 1st element is index 0)

    You can use a variable and then subtract one, to get your logic, that 1 => 'apple'.

    $i = 1;
    $arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
    echo $arr[array_keys($arr)[$i-1]];
    

    Output:

    apple
    

    Well, for simplicity- just use:

    $arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
    echo $arr[array_keys($arr)[0]];
    

    Output:

    apple
    

    By the first method not just the first element, but can treat an associative array like an indexed array.

提交回复
热议问题