8

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)
...
1
  • Small remark: code that reads like this: if … return true; else return false; should always be rewritten to return … === true; or, in a type-safe language, simply to return …;. The if simply makes no sense here, since the condition we are testing already corresponds to the return value. Commented Dec 31, 2011 at 21:52

6 Answers 6

19

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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
}

Comments

5

You could do like this

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

Comments

3

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

Comments

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.