2

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?

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
Luis Urán
  • 49
  • 4

1 Answers1

8

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)), $x);
IMSoP
  • 89,526
  • 13
  • 117
  • 169
CBroe
  • 91,630
  • 14
  • 92
  • 150
  • 2
    I haven't tested to be sure, but I think you can do without the array_values call, because array_combine will iterate over the original array regardless of its keys. – IMSoP Nov 30 '22 at 14:31
  • @IMSoP yeah you're right, the keys of the input data to array_combine don't really matter. – CBroe Nov 30 '22 at 14:37