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 1Array 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, firstFunctions used in this recipe
- array_reverse — Returns an array with its elements in reverse order.