34

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? :)

3
  • 1
    Can't you just use a temp variable to make the swap?
    – j08691
    Jul 2, 2012 at 17:22
  • 1
    If you need to sort the array, you need to define a clear sorting criteria.
    – jeroen
    Jul 2, 2012 at 17:23
  • 4
    Maybe a better question: Why is it out of order in the first place? Jul 2, 2012 at 17:23

10 Answers 10

53

I wrote simple function array_swap: swap two elements between positions swap_a & swap_b.

function array_swap(&$array,$swap_a,$swap_b){
   list($array[$swap_a],$array[$swap_b]) = array($array[$swap_b],$array[$swap_a]);
}

For OP question (for example):

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

array_swap($items,0,1);
var_dump($items);
// OUTPUT

array(3) {
   [0]=> string(4) "home"
   [1]=> string(7) "contact"
   [2]=> string(8) "projects"
 }

Update Since PHP 7.1 it's possible to do it like:

$items = [
  0 => 'contact',
  1 => 'home',
  2 => 'projects'
];

[$items[0], $items[1]] = [$items[1], $items[0]];

var_dump($items);
// OUTPUT

array(3) {
   [0]=> string(4) "home"
   [1]=> string(7) "contact"
   [2]=> string(8) "projects"
 }

It's possible through Symmetric array destructuring.

1
  • The 2nd method can also be done with list(): list($items[0], $items[1]) = [$items[1], $items[0]]; (supported in PHP versions prior to 7.1)
    – glen-84
    Dec 17, 2018 at 13:05
46

Try this:

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

In PHP 7.1+ syntax, you can use this

[$Array[$a], $Array[$b]] = [$Array[$b], $Array[$a]];
4
  • This did not work and returned syntax error, unexpected '=' What would this fall under in PHP 7?
    – Jordan
    Nov 4, 2017 at 3:26
  • (don't forget the semicolon) 7.1, not just version 7 or any sub versions @Jordan Nov 4, 2017 at 19:38
  • @Jordan php.net/manual/en/… Nov 4, 2017 at 19:40
  • It wasn't me. 😀
    – Jordan
    Mar 19, 2018 at 5:17
7

Just use a temp variable to hold one value as you swap the other. Then restore the first with the temp variable. For numbers there are other methods that don't require the use of temp variables but here it's the best (only?) way.

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

print_r($a);
Array ( [0] => contact [1] => home [2] => projects )

$tmp = $a[0];
$a[0] = $a[1];
$a[1] = $tmp;

print_r($a);
Array ( [0] => home [1] => contact [2] => projects )
1
  • 2
    Why PriestVallon's answers has more voteups and is accepted one? Yours come five minutes before his and is actually exactly the same (which makes me fear, that he duped your answer)?
    – trejder
    May 15, 2014 at 13:51
4

New answer: (as others have expressed)

I was not aware of Symmetric Array Destructuring at the time of posting, but that is a functionless, one-liner swapping technique -- I'd use that all day long.

A relevant blog post/tutorial. An example implemention for bubble sorting.

Code: (Demo)

$a = ['contact', 'home', 'projects'];

[$a[0], $a[1]] = [$a[1], $a[0]];

var_export($a);

Old answer:

If you want to avoid using temporary data storage, or love a one-liner use array_replace().

array_replace() will make adjustments in accordance with the indices:

Code: (Demo)

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

var_export(array_replace($a,[$a[1],$a[0]]));

Output:

array (
  0 => 'home',
  1 => 'contact',
  2 => 'projects',
)
5
  • Beside the performance, this only works in the very special case swapping elements with keys 0 and 1. It may be a tempting one-liner for users who want a new array instead of an inplace swap though. In this case, a more explicit form such as array_replace($a, [I => $a[J], J => $a[I]]) would be more readable and less error-prone in my opinion.
    – luciole75w
    Feb 6, 2020 at 19:21
  • Thanks for bringing this to my attention. This answer was not reflecting my current advice, so I have edited. Cheers. Feb 6, 2020 at 21:02
  • Since v7.4 you can do [$a[1], $a[0]] = $a; aswell :)
    – SirPilan
    Feb 11, 2021 at 22:30
  • That is suitable for changing the first two elements in this case, but don't try the same thing with the 2nd and 3rd elements. 3v4l.org/hRbnI @SirPilan Feb 11, 2021 at 22:50
  • In this case you'd prepend a , - example. This is suitable for small arrays only, so i get your point.
    – SirPilan
    Feb 12, 2021 at 8:54
3

Just use a temp variable to hold it. So:

$temp = $array[0];
$array[0] = $array[1];
$array[1] = $temp;

That way you don't lose the value of one of them.

3

I tested the 4 ways proposed to compare the performance:

$array=range(0,9999); //First 10000 natural numbers
$time=-microtime(true); //Start time
for($i=0;$i<1000000;++$i){ //1 Millon swaps
    $a=array_rand($array); //Random position: ~60ms
    $b=array_rand($array); //Random position: ~60ms
    //Using a temp variable: ~70ms
    $temp=$array[$a];$array[$a]=$array[$b];$array[$b]=$temp;
    //Using list language construct: ~ 140ms
    list($array[$a],$array[$b])=array($array[$b],$array[$a]);
    //Using PHP 7.1+ syntax: ~ 140ms
    [$array[$a],$array[$b]]=[$array[$b],$array[$a]];
    //Using array_replace function: ~ 28000ms
    array_replace($array,[$array[$a],$array[$b]]);
}
$time+=microtime(true); //Elapsed time
echo "Time: ",sprintf('%f', $time)," seconds";

Although it is probably not the most comfortable way, using a temporary variable seems to be 2x faster than the next 2 methods, and 400x faster than using the array_replace function.

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

$t = $array[0];
$array[0] = $array[1];
$array[1] = $t;

would be a simple enough approach…

1
$x = array('a', 'b', 'c', 'd');
array_splice($x, 1, 2, array_reverse(array_slice($x, 1, 2)));
var_dump($x);

array_splice can replace a reversed array_slice

1

Solution:

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

list($a[0], $a[1]) = [$a[1], $a[0]];

I have made function for it

function swap(&$a, &$b){
    list($a, $b) = [$b, $a];
}

Usage:

swap($a[0], $a[1]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.