PHP: Comparison within Assignment Statement - php

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

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.

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;

Related

Check if variable has value the opposite way?

I have this PHP if statement that I am trying to firgure out.
I know what the result is, but I have not seen this before (probably my bad).
Who can help me understand the code below? Why is $a showing and not $b? Because $a is first in line?
<?php
$a = 'has a value';
$b = 'this one too!';
if (($href = $a) || ($href = $b)) {
echo $href;
//Result is 'has a value'.
}
?>
|| uses "short-circuit" evaluation. If the first part of the expression is true, then the second part will not be evaluated. In PHP,
The value of an assignment expression is the value assigned.
(quoted from the = documentation)
so in this case the expression ($href = $a) has a value of the assigned value, 'has a value'. That string evaluates to true (see "converting to boolean"), so the second assignment will not be executed.
FYI, for another way to write this that's a little less repetitive, you can do this:
if ($href = $a ?: $b) {
echo $href;
}

In an IF statement, does condition checking continue after one is found to be true (PHP)

For IF statements using OR or similar operators, after one is found to be true, does PHP continue checking the rest or does it stop there?
For example.
if(true == true OR a_checking_function())
Would both be checked, or would PHP just check one?
No, as soon as the first true is found, it goes straight to the code in the braces. If you used an 'AND' keyword, then it would check the second condition.
You may want to look at operator / logic precedence. For example, what would happen for the following conditions?:
if($a = $b AND $c = $d AND $e = $f)...
if($a = $b AND $c = $d OR $e = $f)...
if($a = $b OR $c = $d AND $e = $f)...
http://php.net/manual/en/language.operators.precedence.php
This is VERY simple to test:
<?php
$count = 0;
function testCond($response=false){
global $count;
$count++;
return $response;
}
if(testCond(true) || testCond(false)){
echo "At least one was true.<br>";
}
echo "testCond() was called $count time(s).";
Output:
At least one was true.
testCond() was called 1 time(s).
http://codepad.viper-7.com/bxOiW2
Call a function for each test and have the function increment a global count variable so you get a count of how many times the function was called.

Conversion vs different comparison

If I have a variable which is given a string that could also be a number, as so:
$a = "1";
If I want to check if it is indeed equal to 1, is there any functional difference between
if((int)$a == 1) {
whatever();
}
and
if($a == "1") {
whatever();
}
Here I am thinking about PHP, but answers about other languages will be welcome.
$a = "1"; // $a is a string
$a = 1; // $a is an integer
1st one
if((int)$a == 1) {
//int == int
whatever();
}
2nd one
if($a == "1") {
//string == string
whatever();
}
But if you do
$a = "1"; // $a is a string
if($a == 1) {
//string & int
//here $a will be automatically cast into int by php
whatever();
}
In the first case you need to convert and then compare while in the second you only compare values. In that sense the second solutions seems better as it avoids unnecessary operations. Also second version is safer as it is possible that $a can not be casted to int.
since your question also asks about other languages you might be looking for more general info, in which case dont forget about triple equals. which is really really equal to something.
$a = "1";
if ($a===1) {
// never gonna happen
}
$b = 1;
if ($b === 1) {
// yep you're a number and you're equal to 1
}

PHP || and && logical optimization

I'm a bit of an optimization freak (at least by my definition) and this question has been bugging me for quite a while.
I'm wondering if PHP does some optimization on && and ||:
Take the following example:
$a = "apple";
$b = "orange";
if ($a == "orange" && $b == "orange") {
//do stuff
}
When that code executes, it will check if $a is equal to "orange." In this case it isn't. However, there is an && operator. Since the first part ($a == "orange") already returned false, will PHP still check if $b is equal to "orange?"
I have the same question for ||:
$a = "orange";
$b = "orange";
if ($a == "orange" || $b == "orange") {
//do stuff
}
When it checks if $a is equal to "orange," it returns true. Since that would make the || operator return true, will PHP even check the second part of the || (since we already know it will be true)?
Hopefully I am making sense here, and hopefully somebody has an answer for me. Thank you!
PHP uses short circuit evaluation with binary conditionals (such as &&, || or their constant equivalents), so if the result of evaluating the LHS means the RHS isn't necessary, it won't.
For example...
method_exists($obj, 'func') AND $obj->func();
...is an exploitation of this fact. The RHS will only be evaluated if the LHS returns a truthy value in this example. The logic makes sense here, as you only want to call a method if it exists (so long as you're not using __call(), but that's another story).
You can also use OR in a similar fashion.
defined('BASE_PATH') OR die('Restricted access to this file.');
This pattern is used often as the first line in PHP files which are meant to be included and not accessed directly. If the BASE_PATH constant does not exist, the LHS is falsy so it executes the RHS, which die()s the script.
Yes, PHP short-circuits the && and || operators, meaning that no, the right operand won't be evaluated if the value of the left operand means that it doesn't need to be evaluated. There's no need to optimize them. You can test it like this:
function one() {
echo "One";
return false;
}
function two() {
echo "Two";
return true;
}
one() && two(); // Outputs One
echo "\n";
two() || one(); // Outputs Two
Here's a demo. If there were no short-circuiting, you'd get:
OneTwo
TwoOne

PHP if OR is the second part checked on true?

I know this must be a simple question, but I know that in PHP in a statement like this
if ($a && $b) { do something }
if $a is false PHP doesn't even check $b
Well is the same thing true about OR so
if ($a || $b) { do something }
If $a is true, does it still check $b
I know this is elementary stuff, but I can't find the answer anywhere... Thanks
Evaluation of logical expressions is stopped as soon as the result is known.
logical operators
See Example 1 on the Logical Operators page in the manual.
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
Look at this example:
function foo1() {
echo "blub1\n";
return true;
}
function foo2() {
echo "blub2\n";
return false;
}
if (foo1() || foo2()) {
echo "end.";
}
$b / foo2() isnt checked.
Demo here: codepad.org
If at least one OR Operand is true, there is no need to go further and check the other operands and the whole thing will evaluate to true.
(a || b || c || d || e ||...) will be TRUE if at least one of the operands is true, thus once I found one operand to be true I do not need to check the following operands.
This logic applies everywhere, PHP, JAVA, C...
If you know your truth tables fairly well, then you can probably figure it out yourself. As others have said, PHP will evaluate until it is certain of an outcome. In the case of OR, only one has to be true for the statement to return true. So PHP evaluates until it finds a true value. If it doesn't find one, the statement evaluates to false.
<?php
if(true && willGetCalled()) {}
if(false && wontGetCalled()) {}
if(true || wontGetCalled()) {}
if(false || willGetCalled()) {}
?>

Categories