Home > Software engineering >  Too many if else statement Laravel
Too many if else statement Laravel

Time:11-23

I have a query where user can have 3 option value where they can either just choose one on each option or 2 of either option of even 3 of the option. However, when creating the if else statement in the controller, the if else comes up until 7 statements. Any ideas how to reduce the if else statement. each if else statement gives different input inside, as an example

if (1 !="" && 2 =="" && 3==""){

}elseif(1 =="" && 2 !="" && 3==""){

}elseif(1 =="" && 2 =="" && 3!=""){

}elseif(1 !="" && 2 !="" && 3 ==""){

}elseif(1 !="" && 2 =="" && 3 !=""){

}elseif(1 =="" && 2 !="" && 3 !=""){

}elseif(1 !="" && 2 !="" && 3 !=""){

}else{}

CodePudding user response:

You can use nested if statements instead of this , I think it may help you on this scenario

if(1 !=""){
    if(2 != ""){
        if(3 != ""){
            // all statements are true 
        }else {
            // 1 & 2 statements are true
        }
    }else {
        // only 1 is true 
    }
}else {
    // all statements is false 
}

OR you can do also

    if (1 != "") {
        if (2 != "") {
            if (3 != "") {
                // all statements are true
            }
        }
    } else {
        // all statements is false
    }

CodePudding user response:

you can use this. This is not small but it is easy to understand

if (!empty(1) && empty(2)  && empty(3)){
 return '1';
}

if(empty(1)  && !empty(2) && empty(3)){
 return '2';
}

if(empty(1)  && empty(2) && !empty(3)){
    return '3';
}

if(!empty(1)  && !empty(2) && empty(3)){
    return '1 & 2';
}


if(!empty(1)  && empty(2) && !empty(3)){
    return '1 & 3';
}

if(empty(1)  && !empty(2) && !empty(3)){
    return '2 & 3';
}

if(!empty(1)  && !empty(2) && !empty(3)){
    return 'all empty';
}

here i used return early patten to simplify

  • Related