Reputation: 251
I have an if statement that I want to control with having one field needing input and they have to pick one of the other 2 choices.
if(test1 && test || test3){
//Something here
}
Should I do it like this:
if(test1 && (test2 || test3)){
//do stuff
}
How would I go about doing this. I can't wrap my head around the logic...
Upvotes: 3
Views: 15211
Reputation: 145482
... they have to pick one of the other 2 choices
I'm just throwing a guess out here. If you really want to ensure that one, but only one of the two other options are selected, then you need xor
:
if ($required AND ($and_either XOR $or_other)) {
Upvotes: 1
Reputation: 940
if ($requiredField && ($optional1 || $optional2)) {
/* Do something */
}
For the /* Do something */
bit of code to be executed, the if statement has to evaluate to TRUE
.
This means, that $requiredField
must be TRUE
, and so must be ($optional1 || $optional2)
.
For $requiredField
to be TRUE
, it just needs to be filled in - and for the second part: ($optional1 || $optional2)
either optional1
or optional2
would do it.
Edit:
After rereading the question, it seems that I might have misunderstood you. If the user must enter one specific piece of information, and must choose only one (not both) out of two options - then the following should be used.
if ($requiredField && ($optional1 ^ $optional2)) {
/* Do something */
}
This means that $optional1
or $optional2
must be filled out - but not both of them.
Upvotes: 13
Reputation: 183
Your logic is right but your sintax isnt, you should compare the values of the variables as show, or simply ignore them as saying you are trying to compare them as they are TRUE.
$test1=true;
$test2=true;
$test3=false;
if($test1==true && ($test2==true || $test3==true){ echo "YES";}
This will output YES.
Upvotes: 0
Reputation: 2547
test1 && (test2 || test3)
is very easy to understand from the first place - Choose test1 && (test2 || test3) means one the last two. Very clear.
test1 && test || test3
- doesn't seem to be correct:
test1 = false
test2 = false
test3 = true
false && false || true = true
doesn't actually fit your criteria.
Upvotes: 2
Reputation:
You can have 'nested' if statements withing a single if statement, with additional parenthesis.
if(test1 && (test2 || test3)){
//do stuff
}
Upvotes: 0
Reputation: 4311
From the sound of it, you want the latter:
if ($test1 && ($test2 || $test3)){
//do stuff
}
Think of it as two conditions needing to be met. This gives you those two conditions. The second condition just happens to be another condition. The first option you posted, however, is quite the opposite as it can allow execution if just $test3
is true
Upvotes: 2