webmasters webmasters - 2 months ago 5
PHP Question

Should I use elseif or multiple if clauses

I have this simple if code:

Which is better, doing it with esleif or doing two separate ifs?

if(is_home() && $currentpage == ''){
$catname = 'cars';
} elseif(is_home() && $currentpage != '' && is_page_template('models.php')){
$catname = 'newcars';
}


Two separete if clauses:

if(is_home() && $currentpage == ''){
$catname = 'cars';
}
if(is_home() && $currentpage != '' && is_page_template('models.php')){
$catname = 'newcars';
}


Does the order of if matters? could I place the second if before first?
The question should have been how php treats conditions from more particular to more general?
Should you always start with the more particular ones and work your way up to general?
Or php can sort them through?

The second version would be easier for me since I have allot of if's:)

Answer

This depends what behaviour you want:

If you use elseif, only the first matching block will execute.

$foo = $bar = true;
if($foo) { /* executed */ }
elseif($bar) { /* not executed */ }

When using separate if claused, all matching blocks will execute:

$foo = $bar = true;
if($foo) { /* executed */ }
if($bar) { /* also executed */ }

If the conditions are distinct, i.e. only one is ever true it doesn't really matter. However, by using elseif you avoid useless checks since as soon as one condition evaluates to true no further conditions need to be checked.