I am not understanding this ?quirk? of php at all... as I am looking over other peoples code I see that some people leave out the else statement completely and just place a "return false;" statement.
It seems this trick only works for the return statement and as you can see in the cases below it does not work when echoing text.
This is strange, take case two for example, surely this function is read proceeduraly, so the function will return "true" inside the if statement because the condition is met however when it leaves the if/else statement it should return FALSE because there is no ELSE statement. This DOES NOT happen and the function still returns true.
I can't make sense of this so hopefully someone can explain?
// Case 1
function checkNumber1($number) {
if ($number === 10) {
return true;
} else {
return false;
}
}
$number = 10;
var_dump(checkNumber1($number)); // Returns true
// Case 2
function checkNumber2($number) {
if ($number === 10) {
return true;
}
return false;
}
$number = 10;
echo '<br>';
var_dump(checkNumber2($number)); // Also returns true??
// Case 3
function checkNumber3($number) {
if ($number === 10) {
echo 'true' . '<br>';
} else {
echo 'false' . '<br>';
}
}
$number = 10;
echo '<br>';
checkNumber3($number); // Returns true
// Case 4
function checkNumber4($number) {
if ($number === 10) {
echo 'true' . '<br>';
}
echo 'false' . '<br>';
}
$number = 10;
checkNumber4($number); // Returns true and then false???
The return statement in a function immediately ends execution of the current function and returns control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With