Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to swap the values of two variables

Short answer

Put the variables into an array in reverse order and unpack it right away:

<?php
 
$a = 1;
$b = 2;
 
[$a, $b] = [$b, $a];
 
echo $a, ' ', $b;

Output:

2 1

Array elements

Elements are swapped the same way:

<?php
 
$items = ['first', 'second', 'third'];
 
[$items[0], $items[2]] = [$items[2], $items[0]];
 
echo implode(', ', $items);

Output:

third, second, first

Functions used in this recipe

  • array_reverse — Returns an array with its elements in reverse order.

Thanks for reading!

Donate to the site — we work hard for you.