Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how to array_unshift on an arrayObject

As stated in the title, How do you perform an array_unshift() on a arrayObject, array_push() is obtained by doing an arrayObject->append() but what about unshift ?

Edit: What I've forgot to mention is that i also need in this particular case to preserve existing keys.

like image 485
malko Avatar asked Jul 29 '11 15:07

malko


2 Answers

The API of ArrayObject does not have any function to accomplish this directly. You have several other options:

  • Manually move each element by 1, and set your new value at index 0 (only if you have a numerically index ArrayObject).
 $tmp = NULL;
 for ($i = 0; $arrayObject->offsetExists($i + 1); $i++) {
      $tmp = $arrayObject->offsetGet($i + 1);
      $arrayObject->offsetSet($i + 1, $arrayObject->offsetGet($i));
 }
 $arrayObject->offsetSet($i, $tmp);
 $arrayObject->offsetSet(0, $new_value);
  • Write a class deriving from ArrayObject and add a function prepend (implementation could be the one below).
  • Extract an array, call array_unshift() and create a new ArrayObject with the modified array:
 $array = $arrayObject->getArrayCopy();
 array_unshift($array, $new_value);
 $arrayObject->exchangeArray($array);
like image 140
soulmerge Avatar answered Oct 02 '22 04:10

soulmerge


There is no such functionality in ArrayObject, but you can subclass it to add whatever you need. Try this:

class ExtendedArrayObject extends ArrayObject {
    public function prepend($value) {
        $array = (array)$this;
        array_unshift($array, $value);
        $this->exchangeArray($array);
    }
}
like image 42
lazyhammer Avatar answered Oct 02 '22 03:10

lazyhammer