Get the first element of an array

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

    PHP 7.3 added two functions for getting the first and the last key of an array directly without modification of the original array and without creating any temporary objects:

    • array_key_first
    • array_key_last

    Apart from being semantically meaningful, these functions don't even move the array pointer (as foreach would do).

    Having the keys, one can get the values by the keys directly.


    Examples (all of them require PHP 7.3+)

    Getting the first/last key and value:

    $my_array = ['IT', 'rules', 'the', 'world'];
    
    $first_key = array_key_first($my_array);
    $first_value = $my_array[$first_key];
    
    $last_key = array_key_last($my_array);
    $last_value = $my_array[$last_key];
    

    Getting the first/last value as one-liners, assuming the array cannot be empty:

    $first_value = $my_array[ array_key_first($my_array) ];
    
    $last_value = $my_array[ array_key_last($my_array) ];
    

    Getting the first/last value as one-liners, with defaults for empty arrays:

    $first_value = empty($my_array) ? 'default' : $my_array[ array_key_first($my_array) ];
    
    $last_value = empty($my_array) ? 'default' : $my_array[ array_key_last($my_array) ];
    

提交回复
热议问题