Swap Variables in One Line Using PHP

Swap multiple variables in one line

 

How to swap PHP variables in one line of code. Swap two variables, or swap multiple variables in the same line of code.

Method 1

// You don't need to use a third variable for intermediate storage with this method
$x = "apples";
$y = "red";
list($x, $y) = [$y, $x];

Example 1:

Produces the result:

$x == "red"
$y == "apples"


Method 2

// Swap as many variables as needed
$w = "grapes";
$x = "apples";
$y = "red";
$z = "green";
// The variables can be swapped in any order
// Doesn't have to be reverse order as in the example
list($w, $x, $y, $z) = [$z, $y, $x, $w];

Example 2:

Produces:

$w == "green"
$x == "red"
$y == "apples"
$z == "grapes"

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use