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.

Referral Note: When you purchase through a referral link (if any) on this page, we may earn a commission.
If you're feeling thankful, you can buy me a coffee or a beer