Search code examples
phparraysarrayobject

Reset the Internal Pointer Value of a PHP Array (ArrayObject)


Consider a simple PHP ArrayObject with two items.

$ao = new ArrayObject();
$ao[] = 'a1';  // [0] => a1
$ao[] = 'a2';  // [1] => a2

Then delete the last item and add a new item.

$ao->offsetUnset(1);
$ao[] = 'a3';  // [2] => a3

I'd very much like to be able to have 'a3' be [1].

How can I reset the internal pointer value before I add 'a3'?

I have a simple function that does this but I'd rather not copy the array if I don't have to.

function array_collapse($array) {
    $return = array();
    while ($a = current($array)) {
        $return[] = $a;
        next($array);
    }
    return $return;
}

Solution

  • With the expansion on the question in your comments: you'd have to extend the ArrayObject class to get this kind of behavior:

    class ReindexingArray extends ArrayObject {
        function offsetUnset($offset){
            parent::offsetUnset($offset);
            $this->exchangeArray(array_values($this->getArrayCopy()));
        }
        //repeat for every other function altering the values.
    }
    

    Another option would be the SplDoublyLinkedList:

    <?php
    $u = new SplDoublyLinkedList();
    $array = array('1' => 'one',
                   '2' => 'two',
                   '3' => 'three');
    foreach($array as $value) $u[] = $value;
    var_dump($u);
    unset($u[1]);        
    var_dump($u);
    $u[] = 'another thing';
    var_dump($u);