16

For some reason when removing items from an array I am left with keys like 0, 2, 3, 4, 6, 9 instead of 0, 1, 2, 3, 4, 5. So I am trying to figure out why, and what I can do to fix it without sorting everything via sort() as that will put stuff in order. I just want to re-key in a matter of speaking.

3 Answers 3

41

Use array_values() to get the values of the original array and return them to a new array. That new array will contain new numerical keys.

$new_array = array_values($old_array);
Sign up to request clarification or add additional context in comments.

1 Comment

I have to assume this doesn't work when an array key can potentially be associative, and you want to know about thouse.
5

You should use array_splice() to remove elements from your array so it changes the key the way you wish at the same time.

You have to be careful with array_values() since it will not (or at least might not) work, because it may re-order your numeric indexes. If you added the value at index 0 after the value at index 3, the value at index 0 will be placed at the end of the array returned by array_values(), while it appears first in yours.

Comments

3

Since the keys don't necessarily matter, you can just run your final result array through array_values(). It leaves all the values in the order they already were, resetting all the keys to sequential numeric values.

1 Comment

It's actually false, someone found out that the order is not the order of appearance but the foreach order that is preservered: php.net/manual/fr/function.array-values.php#114941

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.