PHP

How to swap PHP variables?

PHP

Sometimes we need to swap the PHP variables to achieve a specific result. In an old-school way, we define a temporary variable to contain one of the values, then reassess the value. But PHP 7.1 makes this swap easy for us.

<?php
$x = 10;
$y = 20;
// swap variables
$tmp = $x;
$x = $y;
$y = $tmp;

var_dump($x, $y);

Instead of writing five lines of code, we can use the list or [] to swap two variables.

<?php
$a = 30;
$b = 40;
// swap variables
[$a,$b] = [$b, $a];
var_dump($a,$b);