Suppose we want to return a value from a function based on a condition. We can do it in two ways:
function foo($bar) {
if ($bar == 'value1') {
return 'baz';
}
else if ($bar == 'value2') {
return 'qux';
}
}
function foo($bar) {
$result = '';
if ($bar == 'value1') {
$result = 'baz';
}
else if ($bar == 'value2') {
$result = 'qux';
}
return $result;
}
I personally prefer the second approach.
Which way do you thing is better (specially considering longer if/else structures)?
Thanks.
Personally I like the second way, because it’s more readable and you will not miss a return statement anywhere, especially if you have complicated if/else structures.