开发者

PHP: get a single key from object

开发者 https://www.devze.com 2023-01-10 12:38 出处:网络
I have an object with a single key and its value. But I don\'t know the key to access it. W开发者_JAVA百科hat is the most efficient way to get the key without enumerating the object?If you just want t

I have an object with a single key and its value. But I don't know the key to access it. W开发者_JAVA百科hat is the most efficient way to get the key without enumerating the object?


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);


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

$keys = array_keys($array);

echo $keys[0];

// Output: foo

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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号