PHP 布尔值 TRUE/FALSE?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1858139/
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 04:05:11  来源:igfitidea点击:

PHP boolean TRUE / FALSE?

phpboolean

提问by never_had_a_name

I can't figure this out.

我想不通。

If I type:

如果我输入:

function myfunction(){
    ......
    if ...
        return TRUE;
    if ...
        return FALSE;
}

Why can't I use it like this:

为什么我不能像这样使用它:

$result = myfunction();
if ($result == TRUE)
...
if ($result == FALSE)
...

Or do I have to use:

或者我必须使用:

$result = myfunction();
if ($result == 1)
...
if ($result == 0)
...

Or this:

或这个:

$result = myfunction();
if ($result)
...
if (!$result)
...

回答by Tordek

I don't fully understand your question, but you canuse any of the examples you provided, with the following caveats:

我不完全理解您的问题,但您可以使用您提供的任何示例,但有以下注意事项:

If you say if (a == TRUE)(or, since the comparison to trueis redundant, simply if (a)), you must understand that PHP will evaluate several things as true: 1, 2, 987, "hello", etc.; They are all "truey" values. This is rarely an issue, but you should understand it.

如果您说if (a == TRUE)(或者,因为与 to 的比较true是多余的,只是简单地if (a)),您必须明白 PHP 会将几项评估为真:1、2、987、“你好”等;它们都是“truey”值。这很少是一个问题,但你应该理解它。

However, if the function can return more than trueor false, you may be interested in using ===. ===does compare the type of the variables: "a" == trueis true, but "a" === trueis false.

但是,如果该函数可以返回多个truefalse,您可能对使用===. ===确实比较变量的类型: "a" == trueis true,但"a" === true为 false。

回答by Aranxo

If you dont need to use the result variable $result furthermore, I would do the following shortest version:

如果您不需要进一步使用结果变量 $result ,我将执行以下最短版本:

if (myfunction()) {
    // something when true
} else {
    // something else when false
}

回答by YOU

You could do like this

你可以这样做

$result = myfunction();
if ($result === TRUE)
...
if ($result === FALSE)
...

回答by Amarghosh

You can use if($result == TRUE)but that's an overkill as if($result)is enough.

你可以使用,if($result == TRUE)但这if($result)已经足够了。

回答by pcp

if($variable) 
//something when truw
else 
//something else when false

Remember that the value -1 is considered TRUE, like any other non-zero (whether negative or positive) number. FALSE would be 0 obv...

请记住,值 -1 被认为是 TRUE,就像任何其他非零(无论是负数还是正数)数一样。FALSE 将是 0 obv ...