Does PHP's 'return' statement return a boolean by default?

Viewed 247

I'm not quite sure how to ask this but, I have the following PHP function:

<?php

function checkAge($age) {
    return ($age >= 21); 
 }

?>

Which can be used on this conditional:

<?php

if(checkAge(21)) {
    echo 'welcome to the club';
}
else {
   echo 'sorry! you are younger than 21';

} 

?>

When defining the function, I'm only saying return ($age >= 21) and it seems to be returning 'true'. Does that mean that using return like that will return a boolean?

I'm sorry if I'm not being clear, this really confused me :(

Thank you in advance!

2 Answers

return returns whatever you give to it. If what you give to it is an expression, the expression will be evaluated and its result will be returned. Here, you are returning an expression that evaluates to a boolean, so yes your function will return either true or false. So your function checkAge is the same as:

// Just to explain. Don't do this!
function checkAge($age) {
    if ($age >= 21) {
        return true;
    } else {
        return false;
    }
 }

But:

Does PHP's 'return' statement return a boolean by default? No.

What you pass to it is what will be returned. If nothing was passed to it, null will be returned.

return stops the execution of the current module and gives control back to the calling code. See - https://www.php.net/manual/en/function.return.php.

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.

The boolean that you're getting is from your comparison expression $age >= 21. Comparison expressions always return a boolean. See - https://www.php.net/manual/en/language.expressions.php#language.expressions

As an example, these 2 pieces of code are functionally identical. They both compare 2 values and return a boolean.

<?php

if ($age >= 21) {
    ...
}

if (checkAge(21)) {
    ...
}
Related