Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Last key of Object

Tags:

json

object

php

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

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

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

like image 453
Case Avatar asked Jan 31 '13 17:01

Case


1 Answers

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

When the pointer is moved, 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 functionality is identical for arrays How to get last key in an array

like image 155
user20232359723568423357842364 Avatar answered Oct 01 '22 17:10

user20232359723568423357842364