Forum Moderators: coopster

Message Too Old, No Replies

Getting the first element of an associative array

dumb question of the day

         

ngentot

1:58 am on May 16, 2004 (gmt 0)



Can anyone please tell me the easy way to get the first element out of an associative array when you don't know what the key is?

I have this array:

myarray = array("key1" => "val1", "key2" => "val2", and so on)

How can I get "key1" => "val1" returned to me when I don't know the value of key1 is?

Thanks

georgiek50

3:16 am on May 16, 2004 (gmt 0)

10+ Year Member



if you use something like this:

$i = 0;

foreach ($myarray as $key => $value) {
$i++;

if ( $i == 1 )
break;
}

array_splice could also do what you need!

Timotheos

4:07 am on May 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmmm interesting question. Here's my answer.

echo reset($myarray);

This resets the pointer of the array to the first element and it just so happens that it returns the value.

If you want to know the key then use the key function.

echo key($myarray);

Netizen

10:29 am on May 16, 2004 (gmt 0)

10+ Year Member



I think the simplest way of doing this is to use array_slice [php.net].

$output = array_slice($input, 0, 1);

would get you the first element of the array (key and value).

Or, if you don't mind affecting the input array

$output=array_shift [php.net]($input);

which will give you the value in the first element, but remove that from the input array.

dcrombie

11:37 am on May 16, 2004 (gmt 0)



Can't you also do something like this:

list($key1, $val1) = each($myarray);

ngentot

3:14 pm on May 18, 2004 (gmt 0)



thank you all! I ended up using foreach(), looping it only once and then break it. It was so late night and my brain was already fried. But when I have the time, I will try to each of what you guys have suggested. Thanks!