tags:

views:

64

answers:

3

If I have this array:

<?php

$array[0]='foo';
$array[1]='bar';
$array[2]='foo2';
$array[3]='bar3';

?>

And I want to delete the second entry ($array[1]), but so that all the remaining entries' indexes automatically get adjusted, so the next 2 elements whose indexes are 2 and 3, become 1 and 2.

How can this be done, or is there any built in function for this?

+5  A: 

There are several ways to do that. One is to use array_values after deleting the item to get just the values:

unset($array[1]);
$array = array_values($array);
var_dump($array);

Another is to use array_splice:

array_splice($array, 1, 1);
var_dump($array);
Gumbo
+2  A: 

You can use array_splice(). Note that this modifies the passed array rather than returning a changed copy. For example:

$array[0] = 'foo';
//etc.

array_splice($array, 1, 1);

print_r($array);
Tom Haigh
+1  A: 

I always use array_merge with a single array

$array = array_merge($array);
print_r($array);

from php.net: http://us.php.net/array%5Fmerge If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.

easement