search

Home  >  Q&A  >  body text

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?

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粉198670603P粉198670603457 days ago645

reply all(2)I'll reply

  • P粉441076405

    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.

    reply
    0
  • P粉107991030

    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);

    reply
    0
  • Cancelreply