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?
P粉4410764052023-09-13 10:23:40
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
$arr[-1] = 'first';
...then sort, you can do this
array_unshift($arr, 'first');
This inserts 'first'
at index 0
and moves each existing, numerically indexed item up one in the array.
P粉1079910302023-09-13 10:07:27
Use ksort to sort the array, then apply array_values to it. It will re-index keys starting from 0:
$arr = []; $arr[0] = 'second'; $arr[-1] = 'first'; ksort($arr); $result = array_values($arr);