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

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 sayingreturn ($age >= 21)
and it seems to be returning 'true'. Does that mean that usingreturn
like that will return a boolean?
I'm sorry if I'm not being clear, this really confused me :(
Thank you in advance!
Answer
Solution:
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 functioncheckAge
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.
Answer
Solution:
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)) {
...
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the requested url was not found on this server. xampp
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.