Let's say I have this:
$arr = []; $arr[0] = 'second'; $arr[-1] = 'first';
How to change it to $arr[0 => 'first', 1 => 'second']
This is the best I came up with:
$new = []; foreach ($arr as $key => $value) { $new[$key + 1] = $value; } ksort($new);
But as with arrays in php, I'm wondering if there's actually a simple built-in function I can use?
I can't help but wonder if your goal is just to insert a value at the beginning of the array, maybe you're looking for
array_unshift()
?So instead of
...then sort, you can do this
This inserts
'first'
at index0
and moves each existing, numerically indexed item up one in the array.Use ksort to sort the array, then apply array_values to it. It will re-index keys starting from 0: