Get key of 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? Show asked Aug 5, 2010 at 3:16
5
If you just want to access the value, you don't need the key (actually property name) at all:
If you really want the property name, try this:
answered Aug 5, 2010 at 3:24
deceze♦deceze 497k81 gold badges719 silver badges867 bronze badges 2 You can cast the object to an array like this:
And then, for an array that has only a single value, this should fetch the key for that value.
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:
answered Aug 5, 2010 at 3:23
thomasrutterthomasrutter 111k28 gold badges146 silver badges164 bronze badges (PHP 4, PHP 5, PHP 7, PHP 8) key — Fetch a key from an array Descriptionkey(array|object Parametersarray The array. Return Values The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns ExamplesExample #1 key() example
The above example will output: See Also
lhardie ¶ 8 years ago
vinob44 at gmail dot com ¶ 8 years ago
key($array).' FatBat ¶ 10 years ago
Md Tahazzot ¶ 2 years ago
danielmadsv at gmail dot com ¶ 3 years ago
= [ '3' => 14, '1' => 15, '4' => 92, '15' => 65 ];$key_of_max = array_search( max($arr) , $arr);?>
How get the key of an object in 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);
What is $Key in PHP?The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns null .
How do you find array keys?The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.
How do you check if a key exists in an array PHP?PHP array_key_exists() Function
The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
|