Get the first element of an array

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

    Keep this simple! There are lots of correct answers here, but to minimize all the confusion, these two work and reduce a lot of overhead:

    key($array) gets the first key of an array
    current($array) gets the first value of an array


    EDIT:
    Regarding the comments below. The following example will output: string(13) "PHP code test"

    $array = array
    (
       '1'           => 'PHP code test',  
       'foo'         => 'bar', 5 , 5 => 89009, 
       'case'        => 'Random Stuff: '.rand(100,999),
       'PHP Version' => phpversion(),
       0             => 'ending text here'
    );
    
    var_dump(current($array));
    

提交回复
热议问题