PHP: last key of an object

I know that some array functions, such as array_rand, work for objects while you put (array) in front of the object. In this case, I am trying to get the identifier

$this->id = end($this->log->r); 

returns all elements of the last element. I just want to know what the key of this element is. This is a JSON_decoded object.

+4
source share
2 answers

end() sets the pointer to the last property defined in the object and returns its value.

When the pointer moves, you can call the key() function to get the property name

 <?php $object = new stdClass(); $object->first_property = 'first value'; $object->second_property = 'second value'; $object->third_property = 'third value'; $object->last_property = 'last value'; // move pointer to end end($object); // get the key $key = key($object); var_dump($key); ?> 

Outputs

string 'last_property' (length=13)

This function is identical for arrays. How to get the last key in an array

+7
source

You can cast an array before applying the end () method to an object:

 # $menu_items is an object returned by wp_get_nav_menu_items() wordpress method $menu_items = wp_get_nav_menu_items('nav_menu'); $last_item = (array) end($menu_items); print_r($last_item['title']); 
0
source

All Articles