skip to Main Content

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


  1. Sort the array with ksort, then apply array_values to it. It will reindex the keys starting with 0:

    $arr = [];
    $arr[0] = 'second';
    $arr[-1] = 'first';
    
    ksort($arr);
    $result = array_values($arr);
    
    Login or Signup to reply.
  2. To reindex an array with negative integer key values, you can follow these steps to sort the keys and renumber them:

    1. Get the array’s keys using the array_keys function.
    2. Sort the keys using the sort function or asort function if you want to preserve the corresponding values.
    3. Use the array_combine function to combine the sorted keys with the array values, creating a new associative array.
    4. Use the array_values function to reindex the array with numeric keys starting from 0.

    Here’s an example code snippet in PHP:

    $array = [-1 => 'A', 0 => 'B', 1 => 'C', 2 => 'D', 3 => 'E'];
    
    // Step 1: Get the array's keys
    $keys = array_keys($array);
    
    // Step 2: Sort the keys
    sort($keys);
    
    // Step 3: Combine the sorted keys with the array values
    $newArray = array_combine($keys, array_values($array));
    
    // Step 4: Reindex the array with numeric keys starting from 0
    $newArray = array_values($newArray);
    
    print_r($newArray);
    

    Output:

    Array
    (
        [0] => -1
        [1] => 0
        [2] => 1
        [3] => 2
        [4] => 3
    )
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search