How to get the first item from an associative PHP array?

php

Question

If I had an array like:

$array['foo'] = 400;
$array['bar'] = 'xyz';

And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?

1
129
10/24/2009 6:21:05 AM

Accepted Answer

reset() gives you the first value of the array if you have an element inside the array:

$value = reset($array);

It also gives you FALSE in case the array is empty.

257
7/15/2014 4:55:31 AM

Fake loop that breaks on the first iteration:

$key = $value = NULL;
foreach ($array as $key => $value) {
    break;
}

echo "$key = $value\n";

Or use each() (warning: deprecated as of PHP 7.2.0):

reset($array);
list($key, $value) = each($array);

echo "$key = $value\n";

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon