Reputation: 123
Could someone please explain whether or not it is possible to merge a PHP If conditional statement (which contains say AND) with another OR one? And if so, how would one structure the syntax? Which takes priority?
For example, may aim is to achieve something like...
IF ($Var1 == "a" && $Var2 == "z"){
//TRUE
echo "HELLO WORLD";
//<some code block here>
}
OR
IF ($Var3 == "5"){
//TRUE
echo "HELLO WORLD";
//<some code block here>
}
but merged into one if conditional statement, so that I dont have to duplicate my block of code for two if statements (I'm aware I could put the code to be run in the IF statements in functions, but is there another way of doing it).
So in summary (NOTE, brackets below are purely added as a way to group items to indicate my intention for how the code should run/be processed):
(If Var1 = a AND Var2 = b) OR (if Var3 = 5), run block of code.
I'd be really grateful if some could help me out. I've been trying to find this out for months but have got nowhere. Apologies if this has already been discussed here on Stack Overflow, I tried searching but found nothing, although my search terms could've been wrong.
Upvotes: 0
Views: 802
Reputation: 11984
if ($Var1 == 'a' && $Var2 == 'b' || $Var3 == 5)
{
//run block of code.
}
Upvotes: 0
Reputation: 19662
You were almost there:
if ( ($Var1 == "a" && $Var2 == "z") || ($Var3 == "5") ) {
Look carefully at the order of brackets. In just about every language I've come across, a bracket in a conditional indicate that the result of the expression in the bracket is to be evaluated as a whole. PHP is no exception - the first half is only true if both var1 = a and var2 = z, while the other half of the or is only true if var3 = 5. The complete is true when either [var1, var2] = [a,z] or [var3] = [z].
Upvotes: 3
Reputation: 11830
Use like this:-
if (($Var1 == "a" && $Var2 == "z") || ($Var3 == "5")) {
echo "Hello World";
}
Upvotes: 3
Reputation: 6647
Check this:
if (($Var1 == "a" && $Var2 == "z") || ($Var3 == "5")){
//TRUE
echo "HELLO WORLD";
//<some code block here>
}
In fact, you don't need the extra parentheses, as && has a higher priority than ||. However, it helps let everything easy to track.
Upvotes: 4