Which is better?
function test($val = 'a') {
if($val == 'a') {
return true;
}
return false;
}
or
function test($val = 'a') {
if($val == 'a') {
return true;
} else {
return false;
}
}
Effectively, they do the same thing. If $val
isn't 'a', the function returns false. Just personal preference?
Conditional Statements Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.
They are the same. However, for this case, I prefer:
function test($val = 'a') {
return ($val == 'a');
}
I think it comes down to how the comparison "feels" to you. I'd use the first if it seemed like $val being "a" was a special case, and usually the function returned false. I'd use the second if it felt more like it was 50/50 which way it would go.
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