0

Possible Duplicate:
How do you reindex an array in PHP?
PHP reindex array?

I have an array where I delete an element:

unset($array[2]);

After that, the element is gone, but the indices are messed up. I want to indices to be reordered as well. Right now, it has 0,1,3,4,5,....the 2 is missing now. I also used var_dump($array), made no change.

Ideas?

Community
  • 1
  • 1
EOB
  • 2,887
  • 17
  • 42
  • 68
  • 1
    Err: Better [How do you reindex an array in PHP?](http://stackoverflow.com/questions/591094/how-do-you-reindex-an-array-in-php) – hakre Jul 28 '12 at 14:17

2 Answers2

4

Try array_values:


unset($array[2]);
$newArr = array_values($yourArray); //after unset will show array indexed linearly
print_r($newArr);

Sudhir Bastakoti
  • 97,363
  • 15
  • 155
  • 158
0

unset will simply remove the reference to element 2, as in the case. That is why, you don't have index 2 anymore.

What you have to do is implement a function to shift every element left one position, starting with the element one beyond the index from which you want the shift.

After that, unset the very last element.

Shamim Hafiz - MSFT
  • 20,466
  • 38
  • 110
  • 169