PHP: get a single key from object

后端 未结 3 1714
日久生厌
日久生厌 2021-02-15 05:40

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?

3条回答
  •  借酒劲吻你
    2021-02-15 06:33

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

提交回复
热议问题