PHP - switch state

The problem is simple, but I'm looking for a creative solution. We often see arrays, objects that have a property that can be switched (it can be active or inactive, 1 or 0).

What I want is a creative solution (function) for converting from 0 to 1 and from 1 to 0.

Some examples:

// First if ($state == 1) { $state = 0; } else { $state = 1; } // Second $states = array(1, 0); $state = $states[$state]; // Third $state = ($state == 1) ? 0 : 1; 

Is there another, one-line solution for this? Thanks, and enjoy the brainstorming.

+6
source share
3 answers

You can do:

 $state = 1 - $state; 
+20
source

Try this code: $state = !$state

+3
source

If the result is resolved as logical (and it does not have to be a whole swap), you can use the negation operator:

 <?php $state = 0; var_dump(!$state); $state = 1; var_dump(!$state); 

Conclusion:

 bool(true) bool(false) 
+1
source

Source: https://habr.com/ru/post/915482/


All Articles