I retrieved data, with mysqli->fetch_object(), in PHP. How can I get the first item and remove it from the objects, like array_shift does to array? How to emulate array_pop on stdClass also?
Something like:
# $object contains 4 items $first=$object->shift(); $last=$object->pop(); # $object contains 2 items
Preferably no other libraries, nor conversions between object and array needed.
Advertisement
Answer
This will net you the first key from the object property list
https://www.php.net/manual/en/function.get-object-vars.php
$object = new stdClass();
$object->aaa = 'AAA';
$object->bbb = 'BBB';
$object->ccc = 'CCC';
if( empty( $vars = get_object_vars( $object ) ) === false )
{
$firstKey = current( array_keys( $vars ) );
$get = $object->$firstKey; // To get
unset( $object->$firstKey ); // To remove
var_dump( $get );
}
var_dump( $object );
string(3) "AAA"
object(stdClass)#1 (2) {
["bbb"]=>
string(3) "BBB"
["ccc"]=>
string(3) "CCC"
}
In the above code, we’re using an array of keys current( array_keys( $vars ) ) you can replace current with end if you want the first or last key, same way you could also use array_shift or array_pop