Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reindex an array in php without copying it [duplicate]

Tags:

arrays

php

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?

like image 368
Luis Urán Avatar asked Nov 30 '25 12:11

Luis Urán


1 Answers

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);
like image 83
CBroe Avatar answered Dec 03 '25 03:12

CBroe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!