What does && ! mean in PHP?

Asked

Viewed 715 times

3

I am trying to know this, but it appears nowhere. There is a gap between & & e !.

if ( is_home() && ! is_front_page() )
  • 1

    It means that the next condition will be a denied condition, i.e., if the condition is false, it turns true, if it is true, it turns false

  • 1

    In your case, read it like this: If you go home and not on the front page then...

2 answers

14


Spaces usually make no difference to the code. At least in PHP almost always not. Which is a shame because programmers do atrocities and make the code less readable, inconsistent. More or less like they do with natural language. Particularly I would write like this:

if (is_home() && !is_front_page())

It is more obvious the association. Pity that to exaggerate in this can get worse.

The ! (not) is denying the result of is_front_page() which should be a boolean or a data that can be represented as a boolean, such as 0 or another value.

As he is anointed he will be associated with the one on the right and he has a precedence.

The operator && (and) is binary and therefore it will apply in the expressions to the left and right of it. It has a lower precedence than not, then it will be executed later, if the precedence was higher, to obtain the same result, it would have to do:

is_home() && (!is_front_page()))

I put in the Github for future reference.

Space does not change precedence, I only knew a language that did this and it was very confusing.

So this whole expression needs the first method to return a true and the second to return a false, since it will be reversed, then the whole condition of the if will be true and will execute his code block.

In the question on precedence linked above has more information on the and. Has about the not javascript that works the same.

Obviously if we write &&! would be another operator, there is no way the compiler knows that there are two, and since that operator does not exist, it would be an error. This is a point where space is fundamental. In theory the compiler could know why this operator not existing he could automatically understand that are two known operators who ran out of space. But someday you’ll want to create an operator &&! for some reason, it could not because it would be interpreted differently in some situations. Better avoid.

  • 1

    I recommend this site http://php.net/manual/en/language.operators.logical.php

  • Because of 1 space you can understand that is a new operator.

1

That:

if (is_home() && ! is_front_page())

It’s the same thing as that:

if (is_home() && !(is_front_page()))

That is, on behalf of the !, the condition will only be true if the is_home() returns true and the is_front_page() fake return.

Browser other questions tagged

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