phpsplarrayobject

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.


Solution

  • @Dmitry, @soulmerge your answers was good regarding the initial question but was missing the requirement in my edit, but they point me in the right direction to achieve what i was expected here's the solution we came with here at work: (work for php>=5.1)

    public function unshift($value){
      $tmp = $this->getArrayCopy();
      $tmp = array($value) + $tmp;
      $this->exchangeArray($tmp);
      return $this;
    }
    

    these exemple is not exactly the same as the final solution we needed as for our particular arrayObject. We use a given key in array values as key for the values (think of using database rowId as index for each value in the collection). let's call this value "key" here's what the actual array struct looks like:

    array(
      key1 => array(key=>key1,val1=>val1,val2=>val2...),
      key2 => array(key=>key2,val1=>val1_2,val2=>val2_2...),
      ...
    );
    

    so our solution looks more something like this:

    public function unshift($value){
      $tmp = $this->getArrayCopy();
      $tmp = array($value['key'],$value) + $tmp;
      $this->exchangeArray($tmp);
      return $this;
    }
    

    thank's for your answers, if you find a way that work in php5.0 too i'm still interested.