Boolean value switch/invert Boolean value switch/invert php php

Boolean value switch/invert


Yes:

$boolean = !$boolean;

if it's not a boolean value, you can use the ternary construction:

$int = ($some_condition ? 1 : 2); // if $some_condition is true, set 1                                  // otherwise set 2


What about using the Absolute Value function abs() , $val can be "1" or "0" and you want to invert it:

$val = abs($val-=1);

The logic:

Always subtracting "1" from the number and eliminating the "sign".

1 - 1 = 0abs(0) = 00 - 1 = -1abs(-1) = 1


If you want the shortest possible code, XOR the boolean with 1:

$boolean ^= 1;

Strictly this returns an int not a boolean. It doesn't work the same way as $boolean = !$boolean (and is slightly less efficient) but for most purposes it should do the job.