Ali
Ali

Reputation: 267077

Deleting from PHP array and having indexes adjusted

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?

Upvotes: 1

Views: 94

Answers (3)

easement
easement

Reputation: 6139

I always use array_merge with a single array

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

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

Upvotes: 1

Tom Haigh
Tom Haigh

Reputation: 57815

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);

Upvotes: 2

Gumbo
Gumbo

Reputation: 655239

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);

Upvotes: 6

Related Questions