1

We know = is lower precedence than !.

My Question: if the above sentences is true then how to execute the following if() condition

function foo()
{ 
   return false;
}


if(!$a=foo())
{
  echo "Yes, foo() appeared here.";
}
SAR
  • 140
  • 1
  • 8
  • 5
    Operators don't only have a precedence, they also have an [associativity](https://en.wikipedia.org/wiki/Operator_associativity#Right-associativity_of_assignment_operators), and `!` is __right__ associative, whereas `=` is __left__ associative – Mark Baker Mar 04 '16 at 09:46
  • you have a typo, change if(!$a=foo()) to if(!$a == foo()) – St0iK Mar 04 '16 at 09:46
  • 1
    Not sure I understand the question, what do you mean by "how to execute the following ..."? - The logic is fine enough, the if condition is: if `$a` is NOT `true`, then enter – Epodax Mar 04 '16 at 09:46
  • 3
    Quote from the [PHP Docs](http://www.php.net/manual/en/language.operators.precedence.php): `Note: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a. ` – Mark Baker Mar 04 '16 at 09:49
  • @Epodax, I think the OP wants to know HOW things happen. At least I hope do, because I focused on this in my answer! LOL – Ed de Almeida Mar 04 '16 at 09:50

1 Answers1

7

This is an assignment, not a comparison. Besides, you have a function call which is needed to the assignment. Then the order is:

1) Function call returning false;
2) Assignment of false value to $a;
3) Negation of $a as !false, i.e., true.
Ed de Almeida
  • 3,675
  • 4
  • 25
  • 57