PHP commits numeric keys in an array

For some reason, when deleting elements from the array, I leave the keys, such as 0, 2, 3, 4, 6, 9, instead of 0, 1, 2, 3, 4, 5. Therefore, I'm trying to find out why and what I can do to fix this without sorting everything through sort() , as this will lead to ordering things. I just want to talk again in a conversation.

+6
source share
3 answers

Use array_values() to get the values โ€‹โ€‹of the original array and return them to the new array. This new array contains new numeric keys.

 $new_array = array_values($old_array); 
+26
source

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

You have to be careful with array_values() as it will not (or at least not work) because it can reorder your number indices . If you add a value to 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() , then it will appear first in yours.

+5
source

Since keys do not necessarily matter, you can simply run your final array of results via array_values() . It leaves all the values โ€‹โ€‹in the order in which they were already, resetting all the keys to consecutive numerical values.

+3
source

Source: https://habr.com/ru/post/917663/


All Articles