Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: get a single key from object

Tags:

object

php

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?

like image 444
Pablo Avatar asked Aug 05 '10 03:08

Pablo


3 Answers

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);
like image 159
deceze Avatar answered Oct 22 '22 01:10

deceze


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);
like image 22
thomasrutter Avatar answered Oct 22 '22 02:10

thomasrutter


$array = array("foo" => "bar");

$keys = array_keys($array);

echo $keys[0];

// Output: foo

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

like image 21
gpmcadam Avatar answered Oct 22 '22 01:10

gpmcadam