Home > Net >  How to reindex an array in php without copying it
How to reindex an array in php without copying it

Time:11-30

I have this array:

$x = [1 => "uno", 2 => "dos", 5 => "tres", 6 => "cuatro"];

And I need:

$x = [1 => "uno", 2 => "dos", 3 => "tres", 4 => "cuatro"];

I tried using array_values($x) but it starts counting from zero index. How could I do this?

CodePudding user response:

I tried using array_values($x) but it starts counting from zero index.

Use it together with array_combine, and provide an array of values 1, 2, ... created via range to supply the desired keys:

$result = array_combine(range(1, count($x)), array_values($x));
  • Related