operators || or OR in PHP

Asked

Viewed 525 times

1

What’s best and how to use?

I’m trying to run this code for example and it doesn’t work

if(1 !== 1 || 2) {
    echo true;
}

it displays the true being that it was to show only if X (in case 1) was indifferent to 1 or 2.

  • If it is a compound condition it is necessary, repeat the predicate in condition. as for the || and OR is the difference yes.

  • @rray then the way I presented in question is invalid correct?

  • What you expect is if(1 !== 1 || 1 !== 2){ echo true;} ?

  • 2

    In addition to what @rray said (include the predicate in the second part of the condition) I think the error is that you are using the operator ||, when you should be using the &&... You want, as I understand it, to write true if 1 is different from 1 E if 1 is different from 2. Isn’t that : if(1 !== 1 && 1 !== 2) { echo true; } ? For the record, I didn’t deny the question...

  • @gustavox that’s right, thank you for helping me!. About the negatives, well, they do not harm me but the community.

  • Okay, but read the @rray response carefully, because it explains why it’s not working before and gives great tips on operating operators ( that even was very useful to me... I gave +1 in his answer, but now I saw that they gave a negative :/ that tbm was not me! obv).

Show 1 more comment

1 answer

4


if can be translated as se 1 não é identico a 1 OU dois(que é true), when exchanging passwords for logical values, SE(falso OU verdadeira) ENTAO ....

The first part of the sentence(1!==1) is false and the second (only the 2) is considered true for php, because the language works with automatic Casts, it defines a number of values that can be evaluated as false and anything else is true, how sentences are connected through ||(OR logical) a true value is enough to validate the condition.

The difference between || and OR is that OR has less priority or in this case get smart for unexpected results or to add parentheses in condition.

Recommended reading

List of false values for PHP

Qual a diferença entre “&&” e “||” e “and” e “or” em PHP? Qual usar?

  • I still do not understand very well.. In the case of the code that I quoted even with parentheses in the options he gives true.

  • 3

    I don’t understand why there’s so much negativity, but I marked yours for sure, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.