In PHP, if nothing is done in the function and the end is reached, it will be as if it returned false. Because of this, you never need to return false unless there is nothing else in the function. This leaves us with this:
function test($val = 'a') { if($val == 'a') { return true; } }
If the if, elseif or else command has only one command, the brackets ("{" "}") are not needed, which forces us to end up:
function test($val = 'a') { if($val == 'a') return true; }
In PHP, you can actually return a comparison that will be executed immediately before returning it. Here is what some of the people who replied to this post suggested. Doing this leaves us with this code:
function test($val = 'a') { return ($val == 'a'); }
True will be returned if the "($ val == 'a')" block is true, otherwise false will be returned, since this is not true. Logics.
I actually tend to use the second convention that I presented, out of habit. Having seen the beauty of the simplicity of the third presented by others, I will probably switch to this when applicable.
EDIT:
If you want to write code that is easier to understand for non-PHP specialists, another alternative would be:
function test($val = 'a') { if($val == 'a') return true; else return false; }
I would say that not using curly braces in the circumstances described in my second example gives you a more readable code, since curly braces tend to make your code look messy if they don't contain multiple lines.
Emanuel
source share