How to get the first element of an associative array in PHP

I've been always wondering how to get the first element of an associative array in PHP.
For numeric keys you could just do $arr[0] but it'll a little bit different for associative arrays.

Solutions

[code]
$arr = array('one' => 'hello', 'two' => 'world');
[/code]

Solution #1
[code]
reset($arr);
list ($key1, $val1) = each($arr);
[/code]

Solution #2
[code]
$i = 0;
foreach ($arr as $key => $value) {
if (++$i == 1)
echo $key;
break;
}
}
[/code]

Solution #3
[code]
reset($arr);
echo key($arr);
[/code]

Solution #4
[code]
reset($arr);
echo @array_shift(array_keys($arr));
[/code]

Suppressing Warnings such as:
Debug Strict (PHP 5): PHPDocument1 line 6 - Only variables should be passed by reference

Solution #5
[code]
reset($arr);
echo end(array_keys(array_reverse($arr)));
[/code]

Most of solutions can be found on http://www.webmasterworld.com/forum88/3811.htm

Related

Can you come up other solutions ?
Feel free to share your experience by commenting this posting below.

Tags: , , , , ,

8 Responses to “How to get the first element of an associative array in PHP”

  1. Adam Says:

    You can use the key() function for an associative array.

    This will return the first key name, eg $keyname = key($array);

    You can then use next() and prev() to get keys that follow.

    So if i quickly wanted the 3rd key id do this:

    next($array);
    next($array);
    next($array);
    $keyname = key($array);

  2. Svetoslav Marinov Says:

    That's interesting.
    Thanks for sharing your tip.

  3. Mike Says:

    In PHP5,

    $firstelement = reset($array);

    will *return* the value of the first element, and

    $lastelement = end($array);

    will return the last element of the associative array.

    Both function calls have side effects which may matter if you are iterating over the array.

    Yet more obscure ad hoc features of PHP...

  4. Svetoslav Marinov Says:

    That's very interesting info!
    I didn't know that.
    You're right.
    According to php docs here is reset's prototype.
    mixed end ( array &$array )

    Good to know :D

  5. atodorov Says:

    There's one more approach I don't see here:

    $a = array(
    'bar' => array('free' => 1, 'used' => 10),
    '2' => array('free' => 2, 'used' => 20),
    );

    $indexes = array_keys($a);
    $first = $a[$index[0]];

    print_r($first);

  6. chris Says:

    thank you for this information

  7. Svetoslav Marinov Says:

    no problem!

  8. Svetoslav Marinov Says:

    cool. thanks for the comment fellow Bulgarian :)

Leave a Reply