Get first key in a (possibly) associative array?

  • Added:
  • |
  • In: Basic PHP

What's the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this:

foreach ($an_array as $key => $val) break;

Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?

This Question Has 17 Answeres | Orginal Question | Alex S
list($firstKey) = array_keys($yourArray);

Today I had to search for the first key of my array returned by a POST request. (And note the number for a form id etc)

Well, I've found this:Return first key of associative array in PHP

I've done this, and it work.

$data = $request->request->all();
    while ($test = current($data)) {
        echo key($data).'<br />';die();

Maybe it will eco 15min of an other guy. CYA.

$arr = array('key1'=>'value1','key2'=>'value2','key3'=>'key3');
 list($first_key) = each($arr);
 print $first_key;
 // key1

The best way that worked for me was


array_keys gets array of keys from initial array and then array_shift cuts from it first element value. You will need PHP 5.4+ for this.

You can use reset and key:

$first_key = key($array);

It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening.

Just remember to call reset, or you may get any of the keys in the array. You can also use end instead of reset to get the last key.

If you wanted the key to get the first value, reset actually returns it:

$first_value = reset($array);

There is one special case to watch out for though (so check the length of the array first):

$arr1 = array(false);
$arr2 = array();
var_dump(reset($arr1) === reset($arr2)); // bool(true)

This could also be a solution.

$first_key = current(array_flip($array));

I have tested it and it works.

array_keys returns an array of keys. Take the first entry. Alternatively, you could call reset on the array, and subsequently key. The latter approach is probably slightly faster (Thoug I didn't test it), but it has the side effect of resetting the internal pointer.

If efficiency is not that important for you, you can use array_keys($yourArray)[0] in PHP 5.4 (and higher).


# 1
$arr = ["my" => "test", "is" => "best"];    
echo array_keys($arr)[0] . "\r\n"; // prints "my"

# 2
$arr = ["test", "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "0"

# 3
$arr = [1 => "test", 2 => "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "1"

The advantage over solution:

list($firstKey) = array_keys($yourArray);

is that you can pass array_keys($arr)[0] as a function parameter (i.e. doSomething(array_keys($arr)[0], $otherParameter)).


$myArray = array(
    2 => '3th element',
    4 => 'first element',
    1 => 'second element',
    3 => '4th element'
echo min(array_keys($myArray)); // return 1

You could try


You can try this. To get first value of the array :-

        $large_array = array('foo' => 'bar', 'hello' => 'world');

To get first key of the array

        $large_array = array('foo' => 'bar', 'hello' => 'world');
        $large_array_keys = array_keys($large_array);

This is the easier way I had ever found. Fast and only two lines of code :-D

$keys = array_keys($array);
echo $array[$keys[0]];

Interestingly enough, the foreach loop is actually the most efficient way of doing this.

Since the OP specifically asked about efficiency, it should be pointed out that all the current answers are in fact much less efficient than a foreach.

I did a benchmark on this with php 5.4, and the reset/key pointer method (accepted answer) seems to be about 7 times slower than a foreach. Other approaches manipulating the entire array (array_keys, array_flip) are obviously even slower than that and become much worse when working with a large array.

Foreach is not inefficient at all, feel free to use it!

Edit 2015-03-03:

Benchmark scripts have been requested, I don't have the original ones but made some new tests instead. This time I found the foreach only about twice as fast as reset/key. I used a 100-key array and ran each method a million times to get some noticeable difference, here's code of the simple benchmark:

$array = [];
for($i=0; $i < 100; $i++)
    $array["key$i"] = $i;

for($i=0, $start = microtime(true); $i < 1000000; $i++) {
    foreach ($array as $firstKey => $firstValue) {
echo "foreach to get first key and value: " . (microtime(true) - $start) . " seconds <br />";

for($i=0, $start = microtime(true); $i < 1000000; $i++) {
    $firstValue = reset($array);
    $firstKey = key($array);
echo "reset+key to get first key and value: " . (microtime(true) - $start) . " seconds <br />";

for($i=0, $start = microtime(true); $i < 1000000; $i++) {
    $firstKey = key($array);
echo "reset+key to get first key: " . (microtime(true) - $start) . " seconds <br />";

for($i=0, $start = microtime(true); $i < 1000000; $i++) {
    $firstKey = array_keys($array)[0];
echo "array_keys to get first key: " . (microtime(true) - $start) . " seconds <br />";

On my php 5.5 this outputs:

foreach to get first key and value: 0.15501809120178 seconds 
reset+key to get first key and value: 0.29375791549683 seconds 
reset+key to get first key: 0.26421809196472 seconds 
array_keys to get first key: 10.059751987457 seconds


key($an_array) will give you the first key

edit per Blixt: you should call reset($array); before key($an_array) to reset the pointer to the beginning of the array.

Please find the following:

$yourArray = array('first_key'=> 'First', 2, 3, 4, 5);
$keys   =   array_keys($yourArray);
echo "Key = ".$keys[0];

I think this will work.

You can play with your array

$daysArray = array('Monday', 'Tuesday', 'Sunday');
$day = current($transport); // $day = 'Monday';
$day = next($transport);    // $day = 'Tuesday';
$day = current($transport); // $day = 'Tuesday';
$day = prev($transport);    // $day = 'Monday';
$day = end($transport);     // $day = 'Sunday';
$day = current($transport); // $day = 'Sunday';

To get the first element of array you can use current and for last element you can use end

A one-liner:

$array = array('key1'=>'value1','key2'=>'value2','key3'=>'key3');
echo key( array_slice( $array, 0, 1, true ) );

# echos 'key1'

Meet with owner

Sajjad Hossain

Hey, I am Sajjad, working in web development sector since 2012. I love to do amazing things. Let's do a project together.
Connect Social With PHPAns