How can I do an if condition in PHP with multiple conditions? - php

I have 4 variables.
How can I do the following?
$x1='on';
$x2='';
$x3='';
$x4='';
if $x1=='on' and $x2 is empty and $x3 is empty and $x4 is empty , do this else do that ?

Like so:
if($x =='on' && $x2 =="" && $x3 == "" && $x4 == ""){
}else{
}
For future references PHP manual and here's link to expressive operators:
http://php.net/manual/en/language.operators.logical.php

Or, you can use the empty command, like so:
if($x =='on' && empty($x2) && empty($x3) && empty($x4)){
}
else{
}

Related

Why does if($x = 1 && $x == 1) throw error but if ($x == 1 && $x = 2) doesn't in php?

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.

Can I build an if expression ouside the if statement in PHP

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>";

Using 'and' and 'or' in an if/else PHP statement

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..

Set one variable to true based on conditions [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How can I set one variable to true based on other conditions. Here, instead of doing
if ($vara && $varb && $varc)
I'm something like below. Problem is, I'm just not getting something right. Can you please help me?
<?php
$onward = false;
$vara = 11;
$varb = 21;
$varc = 3;
if ($vara == 1)
{$onward = true;}else{$onward = false;}
if ($varb == 2)
{$onward = true;}else{$onward = false;}
if ($varc == 3)
{$onward = true;}else{$onward = false;}
if ($onward)
{
echo "Ok";
}else {echo "Not ok";}
?>
Each of your conditions ignores the result of the previous condition. You need to include the previous state of $onward in each subsequent test:
if ($vara == 1)
{$onward = true;}else{$onward = false;}
if ($varb == 2 && $onward)
{$onward = true;}else{$onward = false;}
if ($varc == 3 && $onward)
{$onward = true;}else{$onward = false;}
This way, varb and varc are only tested if $onward is still true after the previous test.
This is a particularly ugly way of writing code. If you have three large conditions and you don't simply want to join them on one line as in your $vara && $varb && $varc, you should be writing it this way:
$onward = ($vara == 1)
$onward = $onward && ($varb == 2);
$onward = $onward && ($varb == 3);
Any time you're simply returning/setting something to true/false in the branches if your if statement, you should just be returning/setting the condition itself.
That is, this:
if (condition) {
return true;
} else {
return false;
}
should always be written:
return condition;
The problem is, you are overwriting the value of $onward in every if-statement. Just use
$onward = $vara == 1 && $varb == 2 && $varc == 3;
I think you are looking for:
$onward = $vara == 1 || $varb == 2 || $varc ==3;
or
$onward = $vara == 1 && $varb == 2 && $varc == 3;
depending on your goal.
With this:
if ($varc == 3)
{$onward = true;}else{$onward = false;}
$onward will always be false if $varc is not 3.
I'm sure you mean
if (($vara == 1) && ($varb == 2) && ($varc == 3))
{$onward = true;}else{$onward = false;}
or even
$onward = (($vara == 1) && ($varb == 2) && ($varc == 3));
A better way of doing this:
if ($vara == 1) {$onward = true;} else {$onward = false;}
is this:
$onward = ($vara == 1);
You're overwriting the same variable each time, so the first two conditions are actually pointless.
I don't know why you'd want to do this over the first, more succinct approach, which will have the same logical effect:
if ($varc ==== 1 || $varc === 2 || $varc === 3)
$onward = true;
else
$onward = false;
Or even just:
$onward = $varc === 1 || $varc === 2 || $varc === 3;
Beware also of ever doing == 1. In comparisons, data are coerced to their truthy/falsy equivalents, so any truthy value will resolve to true in the comparison == 1. To test that something is literally 1, use ===. (This is a good rule generally unless you know you explicitly want to test for value and not type.)

php if and statement causing problems

Im trying to test a validation using an if statement.
if (($red == "1") && ($blue = "1") ) { $green = "hello"; }
Before this statement runs $blue = 0.
After i run this... $blue changes to 1.
Any ideas why?
You are using = in place of ==:
if (($red == "1") && ($blue = "1") ) { $green = "hello"; }
^^^
As a result (assuming the left side of && returns true) $blue gets assigned "1".
It's one of the most common programming mistakes!! As a way to prevent it from happening programmers put the constant on the left hand side of the the == as:
1 == $blue
so that if by mistake you end up writing = in place of == :
1 = $blue
you get a syntax error as you cannot assign to a constant.
Try this if (($red == "1") && ($blue == "1") ) { $green = "hello"; }
//your code is ($blue ="1") '=' is an assignment operator in php comparison is '=='
you are assigning $blue = 1 instead of comparing that's why $blue is 1
This is because you use =. Use $blue == "1".
Your equal to sing is incorrect in next condistions
if (($red == "1") && ($blue == "1") ) { $green = "hello"; }
Yeah use == instead of =
I would go further and say that maybe you should put literals on the left hand when comparing to avoid such situations.
Like if(1 == $blue) instead of if($blue == 1)
use == or === instead of =.
the '=' is assignment operator, the conditional operators are == or ===
if (($red == "1") && ($blue == "1") )
{
$green = "hello";
}

Categories