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?
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:
$value = current[[array]$object];
If you really want the property name, try this:
$key = key[[array]$object];
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:
$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];
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
Description
key[array|object $array
]: int|string|null
Parameters
array
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 null
.
Examples
Example #1 key[] example
The above example will output:
See Also
- current[] - Return the current element in an array
- next[] - Advance the internal pointer of an array
- array_key_first[] - Gets the first key of an array
- foreach
lhardie ¶
8 years ago
Note that using key[$array] in a foreach loop may have unexpected results.
When requiring the key inside a foreach loop, you should use:
foreach[$array as $key => $value]
I was incorrectly using:
and experiencing errors [the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array]
CORRECT:
FatBat ¶
10 years ago
Needed to get the index of the max/highest value in an assoc array.
max[] only returned the value, no index, so I did this instead.
Md Tahazzot ¶
2 years ago
[Editor note: Or just use the array_keys function]
Make as simple as possible but not simpler like this one :]
$k = array[];
for[$i = 0; $i < count[$arr]; $i++]{
$k[$i] = key[$arr];
next[$arr];
}
danielmadsv at gmail dot com ¶
3 years ago
In addition to FatBat's response, if you'd like to find out the highest key in an array [assoc or not] but don't want to arsort[] it, take a look at this: