phparrayssorting

Move an array element to a new index in PHP


I'm looking for a simple function to move an array element to a new position in the array and resequence the indexes so that there are no gaps in the sequence. It doesnt need to work with associative arrays. Anyone got ideas for this one?

$a = array(
      0 => 'a',
      1 => 'c',
      2 => 'd',
      3 => 'b',
      4 => 'e',
);
print_r(moveElement(3,1))
//should output 
    [ 0 => 'a',
      1 => 'b',
      2 => 'c',
      3 => 'd',
      4 => 'e' ]

Solution

  • 2x array_splice, there even is no need to renumber:

    $array = [
        0 => 'a', 
        1 => 'c', 
        2 => 'd', 
        3 => 'b', 
        4 => 'e',
    ];
    
    function moveElement(&$array, $fromIndex, $toIndex) {
        $out = array_splice($array, $fromIndex, 1);
        array_splice($array, $toIndex, 0, $out);
    }
    
    moveElement($array, 3, 1);
    

    Result:

    [
        0 => 'a',
        1 => 'b',
        2 => 'c',
        3 => 'd',
        4 => 'e',
    ];
    

    redzarf noted: "To clarify $a is $fromIndex and $b is $toIndex"