Search code examples
phpreindexarrayobject

Optimize reindexing ArrayObject


I need an optimized or custom function to update the indexes of object extends ArrayObject

Example:

<?php

class MyCollection extends ArrayObject
{
    // my logic for collection
}

$collection = new MyCollection([
    'first',
    'second',
    'third',
]); // will output [0 => 'first', 1 => 'second', 2 => 'third']

$collection->offsetUnset(1); // will output [0 => 'first', 2 => 'third']

// some reindex function
$collection->updateIndexes(); // will output [0 => 'first', 1 => 'third']

Solution

  • Use exchangeArray to swap out the inner array with one that's been run through array_values. You can combine this into a method on your custom MyCollection class:

    class MyCollection extends ArrayObject
    {
      public function updateIndexes() {
        $this->exchangeArray(array_values($this->getArrayCopy()));
      }
    }
    

    See https://3v4l.org/S8I7Z