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']
2
  • use array_values which would reset the keys? Commented Sep 24, 2018 at 12:36
  • @web-nomad array_values work with array, not with object Commented Sep 24, 2018 at 14:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.