Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean value switch/invert

Tags:

php

boolean

Is there a function for switching/inverting boolean value in PHP?

Like... a shortcut for:

if($boolean === true){
    $boolean = false;
}else{
    $boolean = true;
}
like image 493
tomsseisums Avatar asked Jan 05 '11 11:01

tomsseisums


People also ask

What is boolean invert?

Invert Boolean The Invert Boolean refactoring lets you change the sense of a Boolean method or variable to the opposite one.

How do you reverse a boolean?

Press Ctrl+Shift+R and then choose Invert Boolean.

Can switch condition have Boolean value?

The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true. You can have any number of case statements within a switch.


2 Answers

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 
like image 84
Pekka Avatar answered Oct 18 '22 03:10

Pekka


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 = 0
abs(0) = 0

0 - 1 = -1
abs(-1) = 1
like image 38
Wagner Lipnharski Avatar answered Oct 18 '22 01:10

Wagner Lipnharski