How can I reindex an array with negative integer key values ​​so that item 0,1,2,3,-1 is sorted to -1,0,1,2,3 and then renumbered to 0,1,2,3,4?
P粉198670603
P粉198670603 2023-09-12 12:09:51
0
2
653

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粉198670603
P粉198670603

reply all(2)
P粉441076405

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粉107991030

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template