Adam Tootle
Adam Tootle

Reputation: 519

How do I reindex an array after using unset()?

I'm having a little trouble with losing my array order after using unset(). This is the code I am using.

$id = $_GET['id'];
for ($i = 0; $i < count($my_array); $i++) {
  if ($my_array[$i] == $id) {
    unset($my_array[$i]);
  }
}

Assume that $my_array has 4 items and $my_array[1] is equal to $id. After I unset that, I loop on $my_array and I get an Undefined Offset: 1 error. With print_r($my_array), I get $my_array[0], $my_array[2], and $my_array[3].

I understand perfectly why that's happening. Is there a way to re-index the array so that item 2 'drops' to item 1, and and the rest of the items respectively to the end of the array?

Something like reindex($my_array) would be sweet. I know I could run another for loop with a new array and transfer them manually, but a one step solution would be awesome. I just couldn't find anything anywhere.

Upvotes: 1

Views: 3361

Answers (2)

imagiro
imagiro

Reputation: 472

I just discovered you can also do a

 array_splice($ar, 0, 0);

That does the re-indexing inplace, so you don't end up with a copy of the original array.

Upvotes: 1

Artefacto
Artefacto

Reputation: 97815

Call array_values to reindex the array.

Upvotes: 3

Related Questions