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
Bauer
2010-08-05 03:20:05
This really works for an object? `stdClass::__set_state(array( 'tag1' => 1,))`
Michael
2010-08-05 03:25:32
@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
2010-08-05 03:27:53
I was initially misled as well by the use of the word "key", which is an array term...
deceze
2010-08-05 03:30:59
Sorry guys for misleading ^^
Michael
2010-08-05 03:36:14
+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
2010-08-05 03:23:43
+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
2010-08-05 03:24:43