9

I found that there are many if-else statements, especially nested if else statements, these statements make my code less readable. How to reduce the number of if else statements in PHP?

My tips are as follows: 1.Use a switch statement when it is suitable; 2.use exit() statement when it is feasible; 3. Use ternary statement when it is feasible;

Are there other tips that can reduce if else statements, especially nested if-else statements?

Steven
  • 24,410
  • 42
  • 108
  • 130

7 Answers7

22

Refactor your code into smaller work units. Too much conditional logic is a code-smell and usually indicates that your function needs to be refactored.

Jeff Paquette
  • 7,089
  • 2
  • 31
  • 40
22

Try to use "early return" when possible in order to reduce nesting depth. Try to use boolean expression evaluation.

Example:

function foo($param)
{
    $ret = false;

    if(userIsLoggedIn()) {
        if(is_array($param)) {
            if($param['count'] > 0) {
                $ret = true;
            }
            else {
                $ret = false;
            }
        }        
    }

    return $ret;
}

You could rewrite this like:

function foo($param) 
{
    if(!userIsLoggedIn()) return false;
    if(!is_array($param)) return false;
    return $param['count'] > 0;
}
Max
  • 15,693
  • 14
  • 81
  • 131
  • +1 This is very important as it can reduce your file size by several KB! – Xeoncross Nov 26 '09 at 15:22
  • +1 Also applies to continue, break, throw. You often can keep cyclic complexity low that way and thus make the code more readable. – NikiC Sep 25 '11 at 11:57
  • 5
    Also I personally would use just `return userIsLoggedIn() && is_array($param) && $param['count'] > 0;` here. It's short and concise. – NikiC Sep 25 '11 at 12:00
11

There is an official academic method to refactor and simplify a lot of if conditions, called Karnaugh mapping.

It takes in multiple test conditions and attempts to assist in creating simplified if statements that cover all the required cases.

You can learn more about it from wiki here.

hexacyanide
  • 88,222
  • 31
  • 159
  • 162
iWantSimpleLife
  • 1,944
  • 14
  • 22
  • @WantSimpleLife- can you add more code snippet in your answer. Some time reading over wiki is frustrating. – Gupta May 05 '21 at 03:08
  • Karnaugh map is not really code. It is more a way of looking at the conditions and simplifying them using a table. – iWantSimpleLife Jun 04 '21 at 02:01
3

Use the ternary operator, refactor your code, write a function or a class which does all the necessary if else statements.

NikiC
  • 100,734
  • 37
  • 191
  • 225
streetparade
  • 32,000
  • 37
  • 101
  • 123
3

I work on a lot of code thats full of ever evolving business logic and needs to be modified every other day. Two tips that's certainly helped me keep up with the modifications are: avoid all else statements and return/exit as soon as possible. Never get into deep nesting -> create sub routines/functions.

Replacing all else statements with negated if statements makes your code much easier to read top to bottom (the proximity of the condtion and the code block):

# business logic block
if ( $condition ) {
    # do something
    # code code code
} else {
    # code code code
    return;
}

# refactored:
if ( ! $contition ) {
    # code code code
    return;
}
if ( $condition ) {
    # code code code 
}

Secondly, return/exit as soon as possible. My opinion of course, but I don't see the point in running through any extra conditions/tests when once you've already determined the result of the subroutine, especially when you would like to read the code top to bottom. Removing all ambiguity makes things simpler.

To conclude, I like to avoid using else especially in long lists of BL. Return as soon as you know the result. If the nesting level is more than 2, create sub routines/functions.

smassey
  • 5,875
  • 24
  • 37
1

polymorphism could get rid of a few as well, allthough harder to implement to reduce if/else in PHP as it is not type safe...

NDM
  • 6,731
  • 3
  • 39
  • 52
-1

You can reduce the number of if/else codes by using ternary operator or null coalescing operator like this:

Using the ternary operator: Variable = (Condition) ? (Statement1) : (Statement2);

$age = 20;
  print ($age >= 18) ? "Adult" : "Not Adult";

Output: Adult

By using the null coalescing operator:

// fetch the value of $_GET['user'] and returns 'not passed'
   // if username is not passed
   $username = $_GET['username'] ?? 'not passed';
   print($username);
   print("<br/>");

   // Equivalent code using ternary operator
   $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
   print($username);
   print("<br/>");
   // Chaining ?? operation
   $username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
   print($username);

Output:

not passed 
not passed 
not passed 
ouflak
  • 2,458
  • 10
  • 44
  • 49
Danish Mehmood
  • 111
  • 1
  • 7