phparraysswapdestructuring

Swap the position of two elements in an array by known keys


What would be a good way of swapping the value at key 1 with the value of key 2?

original

Array
(
    [0] => Text1
    [1] => World
    [2] => Hello
)

after

Array
(
    [0] => Text1
    [1] => Hello
    [2] => World
)

Solution

  • If it's a simple as that,

    $tmp = $array[1];
    $array[1] = $array[2];
    $array[2] = $tmp;