$array=array(); $array[key]='val'; $array[keya]='val1'; $array[keyb]='val2'; 

How to choose the first item? $array[0] does not work ...

4 answers 4

If you need to get the value of the first element of an array without knowing its key, you can use the function array_shift () , but it is not always convenient because this element cuts out from the array:

 $array=array(); $array[key]='val'; $array[keya]='val1'; $array[keyb]='val2'; $first= array_shift($array); echo $first; // val print_r($array); // что осталось в массиве Array ( [keya] => val1 [keyb] => val2 ) 

The second way is to use the current pointer.

 $array=array(); $array[key]='val'; $array[keya]='val1'; $array[keyb]='val2'; //reset($array); // можно использовать для полной уверенности, что указатель будет на первом элементе массива (не принципиально) echo current($array); // val 
  • here, reset() is the correct answer in one line - the function returns this very first element of the array, without in any way changing the array itself! @frgs, well done, and wrote a little late. - Sergiks

Once the topic is popular, I will leave my decision just

 $imgs = [ 'first' => '213121321', 'last' => '9898989', ]; $first = reset($imgs); $last = end($imgs); 
  • one
    the only thing that is not said here is end () rewinds the array cursor to the very end of the array, therefore it affects the output of the current () function, but, in principle, who uses it most likely already knows about it. - etki
 foreach($array as $key => $value) { $FirstIndex = $array[$key]; break; } 
     echo $array[key]; 

    What is the question and the answer)