php 布尔值切换/反转

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4603589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:39:10  来源:igfitidea点击:

Boolean value switch/invert

phpboolean

提问by jolt

Is there a function for switching/inverting booleanvalue in PHP?

booleanPHP中是否有切换/反转值的功能?

Like... a shortcut for:

就像...的快捷方式:

if($boolean === true){
    $boolean = false;
}else{
    $boolean = true;
}

回答by Pekka

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

回答by Wagner Lipnharski

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

使用绝对值函数怎么样abs(), $val 可以是“1”或“0”,你想反转它:

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

The logic:

逻辑:

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

总是从数字中减去“1”并消除“符号”。

1 - 1 = 0
abs(0) = 0

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

回答by Gannet

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

如果您想要尽可能短的代码,请将布尔值与 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.

严格来说,这将返回一个 int 而不是一个布尔值。它的工作方式与$boolean = !$boolean(并且效率略低)不同,但对于大多数目的,它应该可以完成这项工作。

回答by Abhinav bhardwaj

Just use !to invert the result so it can be like: $boolean = !(bool)$result;

只是!用来反转结果,所以它可以是这样的: $boolean = !(bool)$result;

回答by A.N

you can do it in one line :

你可以在一行中完成:

<?php
$val = 0 
$val = $val ==1?0:1;  
?>

回答by lazycommit

One touch pick of boolean:

一键选择布尔值:

$detector = !$picker = $detector;

$detector = !$picker = $detector;

回答by user563836

bool can be either TRUE or FALSE.

bool 可以是 TRUE 或 FALSE。

usage : (boolean)$red = varbool(false);
echo $red;

用法 : (boolean)$red = varbool(false);
回声 $red;

for true it will return zero and one for false

如果为真,它将返回零,为假返回一

function varbool($val){ 

    $val +=(-1);
    $val *= (-1);   
    return $val;
}