views:

155

answers:

4

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?

+9  A: 

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
+2  A: 

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

streetparade
A: 

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...

Nicky De Maeyer
+2  A: 

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
+1 This is very important as it can reduce your file size by several KB!
Xeoncross