-1

I am unable to understand why two conditions containing the same values do not return the same result twice.

Look at the variable content :

$quantity = 1;
var_dump(!$cart = true);
var_dump(!$product = false);
var_dump($quantity <= 0);
--------
Output : bool(false) bool(true) bool(false) 

Based on those boolean, I expect the following condition will return TRUE :

$quantity = 1;
var_dump(!$cart = true || !$product = false || $quantity <= 0);
---------
Output : bool(false)

Why ? I was expected this to be TRUE

And why the following exact same condition output what I expected : TRUE

var_dump(false || true || false);
---------
Output : bool(true)

EDIT

I know that = is for assignement. But doing this :

if(!$var = null){
  // $var is not empty
}

Is a way to assign a value and check if this value is null|false|empty|array empty... at the same time.

vincent PHILIPPE
  • 975
  • 11
  • 26
  • 2
    `=` is assignment, use `==` or `===` to check for equality. – Dai Oct 08 '20 at 07:33
  • I know that... But if null is asigned to a value, the result of this expression return false. – vincent PHILIPPE Oct 08 '20 at 07:34
  • The assignment has a different operator precedence than the comparison, i.e. lower than the `||` operator. – Erich Kitzmueller Oct 08 '20 at 07:36
  • No, in that snippet `$var` is still empty, you can check it with `var_dump`. And you would enter the condition because of [casting](https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting), `null` is a _false-y_ value and you are negating it. If `null` was a variable with a non-empty value it won't enter the condition, since it would evaluate to `if (false)`. – msg Oct 16 '20 at 05:28

1 Answers1

3

This is about operator precedence and associativity.

var_dump(!$cart = true || !$product = false || $quantity <= 0);

is the same as

var_dump(!$cart = (true || !$product = false || $quantity <= 0));

Result of (true || !$product = false || $quantity <= 0) is true. !true is false.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • 1
    Ok I see now... That's a verry stupid mistake of mine. So I got to do that ``var_dump((!$cart = true) || (!$product = null) || ($quantity <= 0));`` – vincent PHILIPPE Oct 08 '20 at 08:07