1

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.

9
  • 2
    It's probably simpler to fetch an array and shift/pop as required, then you can convert to an object afterwards if required. But this seems like a strange thing to do on a MySQL result row. What are you trying to achieve?
    – Nick
    Aug 8, 2020 at 2:23
  • Use get_object_vars() to get the keys, get the first key, then perform an unset() on the property
    – Scuzzy
    Aug 8, 2020 at 2:28
  • I try to create a multi-dimensional json with the 1st item being the key of the 1st dimension. I thought there would be array_shift for object. I searched for it, but all people only mentioned array_shift for array but not for object.
    – xam
    Aug 8, 2020 at 2:29
  • @Scuzzy that sounds good, do you mind giving examples? Thank you!
    – xam
    Aug 8, 2020 at 2:31
  • @xam in that case you can just fetch an associative array, you don't need an object, as json_encode will convert an associative array into an object when it encodes it.
    – Nick
    Aug 8, 2020 at 2:40

1 Answer 1

1

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 );

https://3v4l.org/BmpJ6

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.