tags:

views:

155

answers:

5

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?

+2  A: 

You could use each():

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

echo "$key = $value\n";

Or a fake loop that breaks on the first iteration:

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

echo "$key = $value\n";
John Kugelman
Why the downvote?
John Kugelman
Probably because reset() is simpler.
mjs
+5  A: 

reset() gives you the first value of the array.

soulmerge
+3  A: 

There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.

$first = array_shift($array);

current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.

$first = current($array);

If you want to make sure that it is pointing to the first element, you can always use reset().

reset($array);
$first = current($array);
yjerem
+1  A: 

You could use array_shift

Cesar
A: 

Hi All, We can do $first = reset($array);

Instead of

    reset($array);

$first = current($array);

As reset()

returns the first element of the array after reset;

Suryasish Dey