I find myself doing this kind of thing somewhat often:
$foo = true;
$foo = $foo && false; // bool(false)
With bitwise operators, you can use the &=
and |=
shorthand:
$foo = 1;
$foo &= 0; // int(0)
Given that bitwise operations on 1
and 0
are functionally equivalent to boolean operations on true
and false
, we can rely on type-casting and do something like this:
$foo = true;
$foo &= false; // int(0)
$foo = (bool)$foo; // bool(false)
...but that's pretty ugly and defeats the purpose of using a shorthand assignment syntax, since we have to use another statement to get the type back to boolean.
What I'd really like to do is something like this:
$foo = true;
$foo &&= false; // bool(false)
...but &&=
and ||=
are not valid operators, obviously. So, my question is - is there some other sugary syntax or maybe an obscure core function that might serve as a stand-in? With variables as short as $foo
, it's not a big deal to just use $foo = $foo && false
syntax, but array elements with multiple dimensions, and/or object method calls can make the syntax quite lengthy.