never_had_a_name
never_had_a_name

Reputation: 93146

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

Upvotes: 8

Views: 54147

Answers (6)

Max Barannyk
Max Barannyk

Reputation: 39

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

Upvotes: -1

Aranxo
Aranxo

Reputation: 81

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
}

Upvotes: 6

Tordek
Tordek

Reputation: 10872

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.

Upvotes: 19

Amarghosh
Amarghosh

Reputation: 59451

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

Upvotes: 3

YOU
YOU

Reputation: 123791

You could do like this

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

Upvotes: 5

pcp
pcp

Reputation: 1948

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

Upvotes: 0

Related Questions