Search code examples
phparraysswap

Swap the position of two array values without preserving keys


I have an array:

array(
    0 => 'contact',
    1 => 'home',
    2 => 'projects'
);

and I need to swap the 'contact' with 'home', so the array would be like:

array(
    0 => 'home',
    1 => 'contact',
    2 => 'projects'
);

How can I do this with PHP?


Solution

  • Try this:

    $a = array(
        0 => 'contact',
        1 => 'home',
        2 => 'projects'
    );
    $temp = $a[0];
    $a[0] = $a[1];
    $a[1] = $temp;