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!
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With