Creative (crazy) uses of Chain Assignment (PHP)
I was working on a registration screen and had to send some information to the database controller. I had the following code:
$_POST["Username"] = SanitizeData($_POST["Username"]);
$_POST["Password"] = SanitizeData($_POST["Password"]);
$_POST["FullName"] = SanitizeData($_POST["FullName"]);
$_POST["Email"] = SanitizeData($_POST["Email"]);
// Send data to the controller.
sendData($_POST);
What if the $_POST
had more fields, say, $_POST["submit"]
or something, which could be common. So, I made a new array and sent the data this way:
$data = array();
$data["Username"] = $_POST["Username"] = SanitizeData($_POST["Username"]);
$data["Password"] = $_POST["Password"] = SanitizeData($_POST["Password"]);
$data["FullName"] = $_POST["FullName"] = SanitizeData($_POST["FullName"]);
$data["Email"] = $_POST["Email"] = SanitizeData($_POST["Email"]);
// Send data to the controller.
sendData($data);
Now I can be happy that I am sending only the fields in the array I need and nothing else. While doing this, I was thinking what other crazy uses can this have. I looked into a few examples online and found this piece of gem. 💎
Basic Version
What if the right side constant changes, it will be helpful not to reinitialise it again and again for more variables.
$a = $b = $c = 2;
// Ah, we need it as 3!
$a = $b = $c = 3;
What if this 2
gets changed into 3
? There will be only one character change in the above, while in the traditional ones, you have to change three entries of 2
into 3
:
$a = 2; $a = 3;
$b = 2; $b = 3;
$c = 2; $c = 3;
Craziness #1
The previous code can be guessed by many people. One crazy example I saw online was using a loop. Do you want a single loop with one positive numbers and one negative numbers? Here you go.
for ($i = $j = 0; $i < 5; $i++, $j--)
echo "$i $j\n";
The output is crazy like:
0 0
1 -1
2 -2
3 -3
4 -4
Craziness #2
If you think the above is not crazy enough, check this out. Let's say you have two operations happening in a single line of code:
$a = ($b = 1) - 1;
This will leave you with two values:
$a = 0;
$b = 1;
So what exactly happens in the above code is that, you assign 1
to $b
, and the whole assignment operation acts like a return of a immediately invoked function expression that returns the value that was set, which is 1
. And with that, if you subtract another 1
, you get 0
and that's set to $a
.
I haven't seen such crazy uses with chained assignments and it baffled me. So this post. Share your crazy findings in the comments. Until next time! 😁