Suppose I have this:
$arr = [];
$arr[0] = 'second';
$arr[-1] = 'first';
How do I change that to $arr[0 => 'first', 1 => 'second']
This is the best I’ve come up with:
$new = [];
foreach ($arr as $key => $value) {
$new[$key + 1] = $value;
}
ksort($new);
But as with everything with arrays in php, I wonder if there’s actually a trivial built in function I could be using?
2
Answers
Sort the array with ksort, then apply array_values to it. It will reindex the keys starting with 0:
To reindex an array with negative integer key values, you can follow these steps to sort the keys and renumber them:
array_keys
function.sort
function orasort
function if you want to preserve the corresponding values.array_combine
function to combine the sorted keys with the array values, creating a new associative array.array_values
function to reindex the array with numeric keys starting from 0.Here’s an example code snippet in PHP:
Output:
After following these steps, the array will be reindexed with the negative integer keys sorted first, followed by the positive integer keys, and then renumbered with numeric keys starting from 0.