Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first element in PHP stdObject

I have an object (stored as $videos) that looks like this

object(stdClass)#19 (3) {   [0]=>   object(stdClass)#20 (22) {     ["id"]=>     string(1) "123"    etc... 

I want to get the ID of just that first element, without having to loop over it.

If it were an array, I would do this:

$videos[0]['id'] 

It used to work as this:

$videos[0]->id 

But now I get an error "Cannot use object of type stdClass as array..." on the line shown above. Possibly due to a PHP upgrade.

So how do I get to that first ID without looping? Is it possible?

Thanks!

like image 780
Drew Baker Avatar asked Feb 28 '12 00:02

Drew Baker


People also ask

How do I get the first element of an object in PHP?

Alternativly, you can also use the reset() function to get the first element. The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.

How can we get the first element of an array in PHP?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more.

How do I find the first element of an array?

Passing a parameter 'n' will return the first 'n' elements of the array. ES6 Version: var first = (array, n) => { if (array == null) return void 0; if (n == null) return array[0]; if (n < 0) return []; return array.

What is stdClass object in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.


1 Answers

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {   [0]=>   object(stdClass)#20 (22) {     ["id"]=>     string(1) "123"   etc... 

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object 

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element $key = key($obj); 

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4

like image 183
MrTrick Avatar answered Sep 26 '22 15:09

MrTrick