0

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']
Kart Av1k
  • 137
  • 1
  • 6

1 Answers1

1

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

iainn
  • 16,826
  • 9
  • 33
  • 40