views:

69

answers:

6

The key of the associative array is dynamically generated. How do I get the "Key" of such an array?

$arr = array ('dynamic_key' => 'Value');

I am aware that It is possible to access it through a foreach loop like this:

foreach ($arr as $key => $val) echo "Key value is $key";

However, I know that this array will have only one key and want to avoid a foreach loop. Is it possible to access the value of this element in any other way? Or get the key name?

A: 
$keys = array_keys($arr);
echo $keys[0];

Or use array_values() for the value.

Ignacio Vazquez-Abrams
A: 

You can use array_shift(array_keys($arr)) (with array_values for getting the value), but it still does a loop internally.

Lukáš Lalinský
A: 

What about array_keys()?

It does return an array though...

Ganesh Shankar
A: 

do you mean that you have the value of entry and want to get the key ?

array_search ($value, $array) 

Returns the key for needle if it is found in the array, FALSE otherwise.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

more details : http://php.net/manual/en/function.array-search.php

Haim Evgi
+2  A: 

http://www.php.net/key

chris
+2  A: 

Using key() is fine.
If you're going to fetch the value anyway you can also use each() and list().

$arr = array ('dynamic_key' => 'Value');
list($key, $value) = each($arr);
echo $key, ' -> ', $value, "\n";

prints dynamic_key -> Value

VolkerK