views:

503

answers:

5

hi very short question can php return a boolean like this:

return $aantal == 0;

like in java you can

public boolean test(int i)
{
return i==0;
}

or do you Have to use a if contruction? because if i do this.

$foutLoos = checkFoutloos($aantal);

function checkFoutloos($aantal)
{
    return $aantal == 0;
}

echo "foutLoos = $foutLoos";

it echo's

foutLoos =

so not true or false

thanks matthy

+6  A: 

Try it out!

function is_zero($n) {
    return $n == 0;
}

echo gettype(is_zero(0));

The output:

boolean
yjerem
+1  A: 

Yes, you can return a boolean test in the return function. I like to put mine in parenthesis so I know what is being evaluated.

function Foo($Bar= 0) {
    return ($Bar == 0);
}

$Return = Foo(2);
$Type = var_export($Return, true);

echo "Return Type: ".$Type; // Return Type: boolean(true)

In fact, almost anything can be evaluated on the return line. Don't go crazy though, as it may make refactoring more difficult (if you want to allow plugins to manipulate the return, for instance).

sirlancelot
+5  A: 

It returns a boolean, but the boolean is not converted to a string when you output it. Try this instead:

$foutLoos = checkFoutloos($aantal);

function checkFoutloos($aantal)
{
    return $aantal == 0;
}

echo "foutLoos = " . ( $foutLoos ? "true" : "false" );
Sundeep
just to add on, whenever you're doing comparison (using any comparison operators), the result will be boolean. If you're not sure, just use casting to make sure it's boolean. `return (bool)($aantal == 0);`
thephpdeveloper
+1  A: 

yes ideed i found out that when you echo a false you get nothing and true echo's 1 thats why i was confused ;)

matthy
PHP is loosely typed. It will convert you variable to the appropriate context. It's both good and bad.
sirlancelot
I don't think "appropriate" is the word. You want to turn a boolean into a string, so it selects between "1" and ""?
jleedev
A: 

Yes. you can even through in the ternary operator.

function foo($bar == 0) {
    return ($bar) ? true : false;
}
centr0