Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using if...else... or just if... to determine what is returned

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?

like image 425
Nathan Loding Avatar asked Jun 12 '10 21:06

Nathan Loding


People also ask

Is it better to use if or else if?

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.

When should I use else if?

Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.


2 Answers

They are the same. However, for this case, I prefer:

function test($val = 'a') {
    return ($val == 'a');
}
like image 186
Flavius Stef Avatar answered Nov 13 '22 05:11

Flavius Stef


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.

like image 36
Ned Batchelder Avatar answered Nov 13 '22 06:11

Ned Batchelder