1

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?

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.