简体   繁体   中英

PHP AND (&&), OR (||) prioritisation in conditional statements

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.

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.

Use like this:-

if (($Var1 == "a" && $Var2 == "z") || ($Var3 == "5")) {
    echo "Hello World";
}

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

if ($Var1 == 'a' && $Var2 == 'b' || $Var3 == 5)
{ 
//run block of code.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM