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?

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

decezedeceze

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)

keyFetch 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

$array = array(
    
'fruit1' => 'apple',
    
'fruit2' => 'orange',
    
'fruit3' => 'grape',
    
'fruit4' => 'apple',
    
'fruit5' => 'apple');// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name current($array)) {
    if (
$fruit_name == 'apple') {
        echo 
key($array), "\n";
    }
    
next($array);
}
?>

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:
foreach($array as $value)
{
 
$mykey = key($array);
}
?>

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:
foreach($array as $key => $value)
{
 
$mykey = $key;
}
A noob error, but felt it might help someone else out there.

vinob44 at gmail dot com

8 years ago

Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this

$array = array(
   
'0' => '5',
   
'1' => '2',
   
'2' => '0',
   
'3' => '3',
   
'4' => '1');// wrong approachwhile ($fruit_name = current($array)) {

        echo

key($array).'
'
;
      
next($array);
}
// the way will be break loop when arra('2'=>0) because its value is '0', while(0) will terminate the loop

// correct approach

while ( ($fruit_name = current($array)) !== FALSE ) {

        echo

key($array).'
'
;
      
next($array);
}
//this will work properly
?>

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.

reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>

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:

$arr

= [ '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.