tags:

views:

41

answers:

3

I have an object with a single key and its value. But I don't know the key to access it. What is the most efficient way to get the key without enumerating the object?

+2  A: 
$array = array("foo" => "bar");

$keys = array_keys($array);

echo $keys[0];

// Output: foo

See: http://php.net/manual/en/function.array-keys.php

Bauer
This really works for an object? `stdClass::__set_state(array( 'tag1' => 1,))`
Michael
@Michael: My mistake, I assumed you were attempting to retrieve the key from an array. In which case, you will want to cast the object to an array most likely. See @thomasrutter's example: http://stackoverflow.com/questions/3411495/php-get-a-single-key-from-object/3411520#3411520
Bauer
I was initially misled as well by the use of the word "key", which is an array term...
deceze
Sorry guys for misleading ^^
Michael
+2  A: 

You can cast the object to an array like this:

$myarray = (array)$myobject;

And then, for an array that has only a single value, this should fetch the key for that value.

$value = key($myarray);

You could do both those in one line if you like. Of course, you could also do it by enumerating the object, like you mentioned in your question.

To get the value rather than the key, then:

$value = current($myarray);
thomasrutter
+3  A: 

If you just want to access the value, you don't need the key (actually property name) at all:

$value = current((array)$object);

If you really want the property name, try this:

$key = key((array)$object);
deceze