Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use two || and one && in the same if statement in PHP?

You choose two planets A and B in the selector options to measure the distance.

For example:

if (($planetA == "Nova Terra" || $planetB == "Nova Iaponia") && ($planetA == "Nova Iaponia" || $planetB == "Nova Terra")) 
{ 
    echo "From $planetA to $planet B: 290 parsecs"; 
}

else if (($planetA == "Nova Terra" || $planetB == "Novo Mars") && ($planetA == "Novo Mars" || $planetB == "Nova Terra"))
{ 
    echo "From $planetA to $planet B: 230 parsecs"; 
}

You read "from Nova Terra to Nova Iaponia OR from Nova Iaponia to Nova Terra". To = and.

This is similar to like:

if ($planetA == "Nova Terra" || $planetB == "Nova Iaponia") 
{ 
    echo "From $planetA to $planet B: 290 parsecs"; 
}

else if ($planetA == "Nova Iaponia" || $planetB == "Nova Terra") 
{ 
    echo "From $planetA to $planet B: 290 parsecs"; 
}

else if ($planetA == "Nova Terra" || $planetB == "Novo Mars")
{ 
    echo "From $planetA to $planet B: 230 parsecs"; 
}

else if ($planetA == "Novo Mars" || $planetB == "Nova Terra")
{ 
    echo "From $planetA to $planet B: 230 parsecs"; 
}
like image 303
Gustavo Reis Avatar asked Nov 04 '17 05:11

Gustavo Reis


People also ask

Can you use && and || together?

The logical operators && ("and") and || ("or") combine conditional expressions; the ! ("not") operator negates them. The ! has the highest precedence, then && , then || ; you will need parentheses to force a different order.

Can you use multiple || in Java?

We can either use one condition or multiple conditions, but the result should always be a boolean. When using multiple conditions, we use the logical AND && and logical OR || operators. Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.

Can IF statement have 2 conditions?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

How many && operators can be used in one if statement?

There is no limit to the number of && you use in a statement. So it will work with 4, 5, 100. It fails because some of the conditions are falsey.


1 Answers

You just need to interchange your logical operators to get result you want

if (($planetA == "Nova Terra" && $planetB == "Nova Iaponia") || ($planetA == "Nova Iaponia" && $planetB == "Nova Terra")) 
{ 
    echo "From $planetA to $planet B: 290 parsecs"; 
}

else if (($planetA == "Nova Terra" && $planetB == "Novo Mars") || ($planetA == "Novo Mars" && $planetB == "Nova Terra"))
{ 
    echo "From $planetA to $planet B: 230 parsecs"; 
}
like image 120
B. Desai Avatar answered Oct 11 '22 21:10

B. Desai