开发者

PHP boolean TRUE / FALSE?

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开发者_JAVA百科 = 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)
...


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

If you say if (a == TRUE) (or, since the comparison to true is 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.

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


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

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


You could do like this

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


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


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...


Double check you have gettype($result) == bool and NOT string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜