Reputation: 343
In my never-ending quest to optimise my line usage, I've just got a quick question about what exactly can go into as assignment statement in PHP (and other languages too, but I'm working on a PHP project).
In my program I have a certain boolean variable, which is toggled by a few things summarised by an if statement. I thought, hang on, that if statement will evaluate to a boolean value, can I just use that logic in one line, as opposed to wrapping a separate assignment statement inside the if. Basically my question is will:
$myVar = ($a == $b);
be equivalent to
if ($a == $b) { $myVar = true; }
else { $myVar = false; }
As you can see, this saves me one whole line, so it will impact my project hugely. /sarcasm
Upvotes: 0
Views: 1052
Reputation: 11171
Short answer, $myVar = ($a == $b);
is the same as if ($a == $b) { $myVar = true; } else { $myVar = false; }
.
And if you want to be even shorter, you can even remove the (...)
and have it barely $myVar = $a == $b;
Upvotes: 2
Reputation: 2037
What you are looking for is a terinary operation. Something simialar to
$var = ($a === $b ? true : false);
echo $var;
Depending on the evaluation result of $a === $b
the value of $var is then set.
Upvotes: 2