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???
return trueinside your if statement exits the function. In case 4echo 'true'in the if statement does not exit the function, so thenecho 'false'executes as well.returnends the function!, whileechodoes not. So Case 1)10 == 10-> If statement -> return true -> function end Case 2)10 == 10-> If statement -> return true -> function end (Note: Since the return does end the function it will not execute further) Case 3)10 == 10-> If statement -> echo true -> function hits end and stops Case 4)10 == 10-> If statement -> echo true -> function executes further -> echo false -> function endsechoandreturn.