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.
The API of ArrayObject does not have any function to accomplish this directly. You have several other options:
$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);
ArrayObject
and add a function prepend
(implementation could be the one below).array_unshift()
and create a new ArrayObject
with the modified array: $array = $arrayObject->getArrayCopy();
array_unshift($array, $new_value);
$arrayObject->exchangeArray($array);
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);
}
}
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