Get the first element of an array

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

    Try this:

    $fruits = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
    echo reset($fruits)."\n";

    0 讨论(0)
  • 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];
    
    0 讨论(0)
  • 2020-11-22 11:40
    $arr = $array = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
    echo reset($arr); // echoes 'apple'
    

    If you don't want to lose the current pointer position, just create an alias for the array.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 11:44

    You can get the Nth element with a language construct, "list":

    // First item
    list($firstItem) = $yourArray;
    
    // First item from an array that is returned from a function
    list($firstItem) = functionThatReturnsArray();
    
    // Second item
    list( , $secondItem) = $yourArray;
    

    With the array_keys function you can do the same for keys:

    list($firstKey) = array_keys($yourArray);
    list(, $secondKey) = array_keys($yourArray);
    
    0 讨论(0)
  • 2020-11-22 11:44

    Simply do:

    array_shift(array_slice($array,0,1));
    
    0 讨论(0)
提交回复
热议问题