Is it possible to build an if expression outside the if statement itself? Can I concatenate multiple conditions outside the statement and then test them in another if statement?
For example
$var= '$varCars==5 && varBikes == '.$totalBikes;
if(isset($trucks){
$var= $var.' && varTrucks=='.$totalTrucks';
}
if($var){
run some code
}
This was easy in VBScript!!
Harj
Is this what you are after?
$intA = 1;
$intB = 2;
// Returns boolean
$bool = ($intA === 1 && $intB === 2);
if($bool) echo "Yes, it is true<br>";
// if / else
$statement = ($intA === 1) ? 2 : 1;
if($statement === 2) echo "Yep, it is true.<br>";
// if / elseif / else
$statement = ($intA === 2) ? 2 : (($intB === 2) ? 2 : 1);
if($statement === 2) echo "Yep, intA is not equal to 2 but intB is, it is true.<br>";
// if / else concatenate in echo
echo "Hello ".(($intA === 2) ? "John" : "Jane")." do you want to grab some coffee?<br>";
Related
In php the following code gives a warning of undefined variable $x:
if($x = 1 && $x == 1)
I thought it was equivalent to if( ($x = 1) && ($x == 1) ), but that's not the case. I've been told, it's because && has higher precedence than =, which causes the expression to get converted to:
if($x = (1 && ($x == 1)))
So far so good, but now consider:
$x=1; if($x == 1 && $x = 2)
This doesn't throw error. Why doesn't it get converted to:
$x=1; if( (($x == 1) && $x) = 2 )
I've been told thats due to = being right assosiative, but https://www.php.net/manual/en/language.operators.precedence.php says When operators have equal precedence their associativity decides how the operators are grouped.. Here we have =, && and == all being of different precedence.
P.S; My actual code is if($result != false && $res = $stmt->get_result()), which has been copied from some other reputable source, so seems like not using unneeded parenthesis is common in php.
I've played with several conditions and below is what I've got.
First, let's consider that we init $x before if statements to avoid undefined variable notice.
Second, let's confirm the precedence for operators:
== is applied 1st
&& is applied 2nd
= is applied 3rd
This returns true:
$x = 1;
if ($x = 1 && $x == 1) {
echo 'true';
} else {
echo 'false';
}
It goes like ($x = (1 && ($x == 1))) -> ($x = (1 && true)) -> ($x = true) -> true.
If we compare $x to another value than the assigned one we will get false:
$x = 1;
if ($x = 2 && $x == 2) {
echo 'true';
} else {
echo 'false';
}
It goes like ($x = (2 && ($x == 2))) -> ($x = (2 && false)) -> ($x = false) -> false.
The last one returns true:
$x = 1;
if ($x == 1 && $x = 2) {
echo 'true';
} else {
echo 'false';
}
It goes like ((($x == 1) && $x) = 2) -> ((true && $x) = 2) -> (true = 2) -> true.
The last comparison can't be interpreted by PHP so it's an approximate view.
It looks like the last action (true = 2) totally depends on the left operand. If we put $x = 2; we will get (false = 2) -> false.
I'm not sure about the last one and here is the only place were some mistakes can happen.
Otherwise, it looks like precedence works as expected.
Anyway, I always put parenthesis for an assignment action inside if operator (especially inside ternary if) to be sure that I will get what I expect.
I don't think this affects performance or readability too much, but it may prevent some logical errors.
UPDATE:
Concering your code if($result != false && $res = $stmt->get_result()) it's not correct to compare it to if($x == 1 && $x = 2) because in your code are two different variables.
In this case logical operator will not call the second part at all if the fisrt one is false, see the 1st example here
UPDATE-2:
After the discussion under this answer we can see that the last conditions ($x == 1 && $x = 2) work like like (($x == 1) && ($x = 2)) -> ((1 == 1) && 2) -> true and $x becomes 2 after it.
Is there a way to get the true statement from $this if condition:
$a = 1;
$b = 3;
$c = 7;
if ($a == 3 || $b == 4 || $c == 7) {
echo "The true statement was: ";
}
I expect to get this output:
The true statement was: 7
Is it possible to do this in PHP?
Or better to say how can i check which statement has triggered the if condition?
You can't without multiple conditions. Whatever answer you will get here eg:
Inline if statements
Wrap in a function
Condition result assignment in the condition
Switch
Loops
etc. Will always require you to have multiple conditions.
If you don't mind multiple conditions and just looking for most elegant way to write it, thats another question and we can help.
This can only ever show 1 true statement because of how the if works:
$a = 1;
$b = 3;
$c = 7;
if (($t = $a) ==3 || ($t = $b) == 4 || ($t=$c) == 7) {
echo "The true statement was: $t";
}
What happens here is it sets $t to each variable and then checks if the assignment result (which is the value) was successful. Since this is an || then it stops at the first success and so $t will have the last compared value.
Try this.
<?php
$day = 1;
$month = 3;
$year = 2017;
$str = "The true statements are: " . ($day == 3 ? "$day, " : "") . ($month == 4 ? "$month, " : "") . ($year == 2017 ? "$year, " : "");
echo substr($str, 0, strlen($str) - 2);
?>
If I understand correctly, this should work.
The strlen($str) -2 is to remove the trailing ", ".
Here is a solution with boolean variables:
$day = 1;
$month = 3;
$year = 2017;
$cday = $day == 3;
$cmonth = $month == 4;
$cyear = $year == 2017;
if ($cday || $cmonth || $cyear) {
echo "The true statements are: ";
if($cday) echo "$day<br>\n";
if($cmonth) echo "$month<br>\n";
if($cyear) echo "$year<br>\n";
}
This might help -
// actual values
$day = 1;
$month = 3;
$year = 2017;
// values & variable names to check
$checks = array(
'day' => 1,
'month' => 4,
'year' => 2017,
);
// Loop through the checks
foreach($checks as $check => $value) {
// compare values
if($$check == $value) {
// output and stop looping
echo "The true statement was: $check -> $value";
break;
}
}
Demo
I am attempting to use both AND and OR statements in my IF/ELSE statement, but I cannot get the desired effect.
What I would like to achieve is that if either 'a' or 'b' has a value of '1' but both 'c' and 'd' must be 1 then I get 'Yes'.
All my attempts have given me either 'Yes' or have not worked (blank screen).
<?php
$a = "0";
$b = "1";
$c = "1";
$d = "1";
if (($a == "1") || ($b == "1") && ($c == "1") && ($d == "1")) {
echo "Yes";
}
else {
echo "No";
}
?>
Thank you.
You need and extra parenthesis, to make sure the evaluation order will be done correctly, like in math:
if ( ( ($a == "1") || ($b == "1") ) && ($c == "1") && ($d == "1")) {
^ ^
That way, let's say for example:
$a = 1;
$b = 2;
$c = 1;
$d = 2;
The first parenthesis will be evaluated as true || false. The final result will be true.
So now you have true && ($c == "1") && ($d == "1")
$c = 1, so again, the next evaluation will be true && true && ($d == 1)
$d = 2, so the next round will be true && true && false, final result, in this example, will be false.
You need to add parenthesis.
Why?
Because inner parenthesis are evaluated first before outer parenthesis. Take this example:
((1 == 1 && (2 == 2)) || 3 == 3)
What will be evaluated first? The 2 == 2 then the 1 == 1 and then the 3 == 3. In your if condition, because you are mixing AND's and OR's, you will not get the desired affect.
( (($a == "1") || ($b == "1")) && ($c == "1") && ($d == "1") )
Should work for you. In fact you can do this so that it looks even better:
(($a == 1 || $b == 1) && $c == 1 && $d == 1)
Because it is not necessary to put 1 in quotes ie: "1". PHP's truthiness will evaluate 1 == "1" to be true. However if you wanted to check for an actual string that contains 1, then you would use the === operator.
$a = 1;
$b = "1"
$a == "1"; // true
$b == 1; // true
$a === "1"; // false
$b === "1"; // true
However for more information go here: http://php.net/manual/en/language.operators.precedence.php
The equality operators will be evaluated first, then &&, then ||. Parentheses will be evaluated before anything else, so adding them can change the order.
Check the answer In Java, what are the boolean "order of operations"?
It will always echo a Yes because PHP interpreter places The AND operation before the OR operation.
So your if statement interpretes like this:
If
a = 1 or b = 1 and c = 1 and d = 1
then
echo 'Yes'
else
echo 'No'
That's why you always get a yes..
I have a variable $allrule = '(1 == 2) && (2 == 2)';
when i check if($allrule), it returns true because $allrule is treated as string. So i want to convert $allrule as condition of if statement. how can we do it.
This solution uses eval() which is pure evil, but since it wasn't stipulated not to do so...
$allrule = '(1 == 2) && (2 == 2)';
$result = eval("return (".$allrule.");"); // $result will be false
Expanded Example*:
$allrule = "(1433861812 > 1433694000) && (1433861812 > 1433771400) && (1433861812 > 1433944200)";
$result = eval("return (".$allrule.");");
if($result) {
echo "true";
} else {
echo "false"; // will echo "false"
}
*from comments
I am checking 3 variables are equals to zero inside if condition , currently i am doing some thing like this
if($diff_colour_code==0 && $diff_upholstery_code==0 && $big_diff==0 )
is there any better way to do this
I am thinking a way like
if($diff_colour_code==$diff_upholstery_code==$big_diff==0 )
Please help , Thanks in advance .
This should work for you:
You can give the function as many arguments as you need!
<?php
$diff_colour_code = 0;
$big_diff = 0;
$diff_upholstery_code = 0;
function zeroCheck() {
foreach(func_get_args() as $arg)
if($arg == 0)
continue;
else
return false;
return true;
}
if (zeroCheck($diff_colour_code, $big_diff, $diff_upholstery_code))
echo "all are 0!";
?>
you can use ! as :
if(!$diff_colour_code && !$diff_upholstery_code && !$big_diff )
You could do something like this:
$var1 = 0;
$var2 = 0;
$var3 = 0;
$array = compact("var1", "var2", "var3");
$countValues = array_count_values($array);
if($countValues[0] == count($array)){
echo "yes";
}else{
echo "no";
}
or this
if(($var1 == 0 && $var1 == $var2 && $var2 == $var3)){
echo "yes";
}else{
echo "no";
}