How to reindex an array?

By using sort($array);

See PHP documentation here.

I'd recommend sort over array_values as it will not create a second array. With the following code you now have two arrays occupying space: $reindexed_array and $old_array. Unnecessary.

$reindexed_array = array_values($old_array);


array_splice($old_array, 0, 0);

It will not sort array and will not create a second array


From PHP7.4, you can reindex without a function call by unpacking the values into an array with the splat operator. Consider this a "repack".

Code: (Demo)

$array = array(
  0 => 'val',
  2 => 'val',
  3 => 'val',
  5 => 'val',
  7 => 'val'
);

$array = [...$array];

var_export($array);

Output:

array (
  0 => 'val',
  1 => 'val',
  2 => 'val',
  3 => 'val',
  4 => 'val',
)

Note: this technique will NOT work on associative keys (the splat operator chokes on these). Non-numeric demo

The breakage is reported as an inability to unpack string keys, but it would be more accurate to say that the keys must all be numeric. Integer as string demo and Float demo


Use array_values:

$reindexed_array = array_values($old_array);

Tags:

Php

Arrays