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: array_keys, array_shift, associative array, first, php, php array
January 26th, 2009 at 10:09 am
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);
January 26th, 2009 at 9:23 pm
That's interesting.
Thanks for sharing your tip.
May 18th, 2009 at 9:47 pm
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...
May 19th, 2009 at 5:18 pm
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
March 1st, 2010 at 4:34 pm
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);
May 2nd, 2010 at 2:35 pm
thank you for this information
May 7th, 2010 at 5:12 pm
no problem!
May 7th, 2010 at 5:18 pm
cool. thanks for the comment fellow Bulgarian