How to get first value from array?


I have a dynamically generated array which has data like following:

    [4] => 3
    [3] => 1

How to get the first value from the array as I don’t know whats going to be the values. So as in this the first is 4 and it can be anything.

How do I get the first value ? I want to get both key and its value.

echo array{0} or something like that. Please help.


$array = array(
  4 => 1,
  2 => 6

  Just to be safe

  Get first value
echo current($array), PHP_EOL ;

  Get key for first value
echo key($array), PHP_EOL ;

here one (other) way:

$x = array ( 4 => 3 ,  3 => 1 );
$y = array_chunk($x, 1, 1);
var_dump( $y[0]);


Thanks for the reply. I just found this function in php manual:

$keys = array_keys($array);

I got the first value then using $keys[0].

Then echo array[$keys[0]];

Works! :slight_smile:


You can get a list of all the array keys by using the array_keys() function.

$myArray = array (4 => 3, 3 => 1);
$arrayKeys = array_keys($myArray);

// the first element of your array is:
echo $myArray[$arrayKeys[0]];

For what it’s worth, reset() will return the first value (negating the need for calling current()).

That seems a little strange, I’d expect (wrongly, apparently) a true/false from that.


It behaves similarly to the other associated functions, here’s a quick overview of what they return.

[INDENT]reset - First value in array
end - Last value in array
each - Array containing key/value pair (twice) for current item
current - Current value
key - Current key
next - Next value in array
prev - Previous value in array[/INDENT]

They will return FALSE if the function cannot get what it wants (e.g. reset() with an empty array, prev() when at the beginning of an array, etc.).

If you only want the value, you can also use:

$array = array('one', 'two', 'three');
list($first, $second, $third) = $array;
echo $first;