Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Where to place return 'false' value?

Tags:

php

Is one of the following functions better than the other, in terms of where to place the 'return false' statement?

Function #1:

function equalToTwo($a, $b)
{
    $c = $a + $b;
    if($c == 2)
    {
        return true;
    }
    return false;
}

Function #2:

function equalToTwo($a, $b)
{
    $c = $a + $b;
    if($c == 2)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Thanks!

like image 293
Mike Moore Avatar asked May 13 '10 03:05

Mike Moore


People also ask

What is return false in PHP?

return $oh || false does not work in PHP like it works in JavaScript. It would always return a boolean value (true or false). – Matthew. Apr 13, 2011 at 15:15. $result = $oh OR false will work as expected, since OR has a lower precedence than the return (but the second option must be a boolean).

How check return false in PHP?

The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.

Is return 0 and return false the same?

return 1 in the main function means that the program does not execute successfully and there is some error. return 0 means that the user-defined function is returning false. return 1 means that the user-defined function is returning true.

Can you return two values in PHP?

A function can not return multiple values, but similar results can be obtained by returning an array.


2 Answers

There is no functional difference between the two; you should choose whichever one is most obvious and readable.

I would usually use an else.

Note that your particular example should be written as

return $c == 2;
like image 55
SLaks Avatar answered Sep 23 '22 01:09

SLaks


What about just:

return ($c == 2);
like image 24
dreamlax Avatar answered Sep 23 '22 01:09

dreamlax