0

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

3
  • 4
    You can take a look at the ternary operator. But don't make your code unreadable just by saving code lines. Commented Mar 4, 2016 at 0:48
  • 2
    I'd close this question, as ternary operator is a common knowledge. At the same time - I don't understand the huge impact of economy of lines of code. I'd also recommend you, Daniel, to read-up on PSR-2, it will definitely have huge impact on your PHP project ;) php-fig.org/psr/psr-2 Commented Mar 4, 2016 at 0:54
  • 1
    Yeah, I was asking more out of curiosity than anything. Obviously an actual if statement makes it a bit more readable. I wasn't aware of the ternary operator. I did a bunch of googling for "Comparison inside assignment" and the like, but knowing that keyword would have helped. Commented Mar 4, 2016 at 1:14

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.