Ryan Chandler

Quickly swap 2 variables in PHP

You can use PHP's list() construct to quickly swap the value of 2 variables. You can also use the short-hand list notation.

$a = 2;
$b = 1;

list($a, $b) = [$b, $a];

Now $a will hold the value of $b = 1 and $b will hold the value of $a = 2.

The list() syntax is a bit outdated now, so you could also use the short-hand notation.

$a = 2;
$b = 1;

[$a, $b] = [$b, $a];

A `clamp` function for PHP

You can use this function to "clamp" a number between a min and max.

function clamp($subject, $min, $max) {
    return max($min, min($max, $subject));
}

This is perfect for when you need a number to always be within a range, e.g. percentages must be greater than 0 and no more than 100.