I was wondering if complicated if/else structures in my PHP code could be a bad design decision. Does having a lot of if statements make PHP run slow, site load slower etc?
This is the code:
(I’ve no idea how wordpress handles is_page etc.)
<?php
if (is_page()) {
//
if (is_page(122)) {
//subscribe page
echo "subscribe page";
}
elseif (is_page(1263)) {
//photography course
echo "photography course page";
}
elseif (is_page(array(210,184,128))) {
//210 copyright policy, 184 privacy policy, 128 contact
echo "this is either copyright policy, privacy or contact page!";
//nothing happens here, we don't need social buttons on these pages.
}
elseif (is_page(array(379,71,7,45,124,8,105,175,9,125,110))) {
//379 photo galleries, 71 car photos, 7 conceptual, 45 event photos, 124 fashion, 8 landscape, 105 misc, 175 journalism, 9 portrait, 125 street photography, 110 travel
echo "gallery pages and albums";
}
else {
//any other page
echo "any other page";
}
//
}
elseif (is_single()) {
//
if (in_category(array(147,196,35))) {
//147 car photography, 196 car wallpapers, 35 photo stories
echo "photo posts";
}
else {
//any other post
echo "any other post";
}
//
}
elseif (is_archive()) {
//
//any category
echo "this is archive template"
}
//
?>
Nope. In fact, it’ll actually speed it up in most cases (because it’s allowed to skip over blocks of code).
The only time large numbers of if statements will slow it down is if the condition you’re checking requires processing. An example would be something like:
Ever iteration through the loop checks if
count($some_array) == 0. That means that every pass, PHP has to go and manuallycountthe number of items in$some_arraybecause it may have changed. This also applies to the stop condition in a for loop. This is because a for loop can always be rewritten as a while loop:is the same as…
If you’re considering merging a bunch of if statements into one: don’t, you won’t get any benefits. PHP does short circuiting which means that if it reaches a point where it knows what the outcome will be, it’ll skip the rest.
For example, consider
$a = 5; if ($a > 0 || $b > 100 || $c > 200) {}.Once PHP sees that the
$a > 0condition is satisfied, the whole statement resolved to true (because of the usage of OR values) and doesn’t bother to check$b > 100or$c > 200.So to answer your question: unless you have an ungodly number of conditionals that each require complicated calculations or have side effects, you can usually consider the quantity of them to be inconsequential.
However, as others have noted, having too many if statements can reduce code readability. In many cases, if you can remove a conditional without it affecting the behavior of the code, then you didn’t need it to begin with.