PHP: get one key from an object

I have an object with one key and its value. But I do not know the key to access it. What is the most efficient way to get a key without listing an object?

+6
object php
source share
3 answers

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

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

If you really need a property name, try the following:

 $key = key((array)$object); 
+21
source share

You can pass an object to an array as follows:

 $myarray = (array)$myobject; 

And then for an array that has only one value, this should extract the key for that value.

 $value = key($myarray); 

You can do this on one line if you want. Of course, you can also do this by listing the object, as you mentioned in your question.

To get a value, not a key, follow these steps:

 $value = current($myarray); 
+4
source share
 $array = array("foo" => "bar"); $keys = array_keys($array); echo $keys[0]; // Output: foo 

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

+3
source share

All Articles