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:)
This depends what behaviour you want:
If you use
elseif, only the first matching block will execute.When using separate
ifclaused, all matching blocks will execute:If the conditions are distinct, i.e. only one is ever true it doesn’t really matter. However, by using
elseifyou avoid useless checks since as soon as one condition evaluates to true no further conditions need to be checked.