Jump to content

How do you deal with multiple/nested IF/ELSE statements (styling Q)


enveetee

Recommended Posts

Hi

 

As I get deeper into PHP I am always coming across a situation where I have multiple condition testing. I end up coding thus:

 

If (condition){

 

     } else {

 

}

This can get very messy when you get 4 or 5+ conditions to test for.

 

In other languages, I have used loops and then use break out of the loop if a condition fails:

 

WHILE(TRUE)

 

     if (!condition) {

          break;

     }

 

break;

}

 

 

Can anyone comment or make a better suggestion pls

 

Thanks

 

Link to comment
Share on other sites

in programming, there are multiple different ways of accomplishing anything and the best answer depends on what you are actually doing.

 

if each later test is preformed based on the result of the previous tests, you would need to write out the nested logic as needed. if the tests are independent and are just testing different values in one variable, you would instead use a switch/case statement or even simpler, a look-up array to map one value to another.

 

short answer: it depends.

 

do you have a specific problem you are trying to solve?

Link to comment
Share on other sites

in the case of looping and testing values, again it depends.

 

if this is data from a database query and all you are interested in is if the data was found, you would perform the test in the database query. if validating if a variable is one any of many permitted values, having the permitted values in an array and using php's array functions would produce the most efficient code, rather than looping until a value is found or not are found...

Link to comment
Share on other sites

One thing I see a lot of, is people creating deeply nested logic for error checking in this fashion:

if(notErrorCondition1)
{
    if(notErrorCondition2)
    {
        if(notErrorCondition3)
        {
            if(notErrorCondition4)
            {
                //Perform actions for success scenario
            }
            else
            {
                echo "Error condition 4";
            }
        }
        else
        {
            echo "Error condition 3";
        }
    }
    else
    {
        echo "Error condition 2";
    }
}
else
{
    echo "Error condition 1";
}

This irritates the hell out of me because it makes it nearly impossible to "view" the logic. The nested if/else statements are bad enough. But, the worst part is the separation of the condition check and the associated error. The first error check is associated with the last error result. 99% of the time, that logic can (and should) be rewritten to make it so you can "see" the logic. I always write my error condition to check for the presence of the error (not the lack of an error) so I can associate the error logic with the check. Using the above, here is one way it could be rewritten

if(errorCondition1)
{
    echo "Error condition 1";
}
elseif (errorCondition2)
{
    echo "Error condition 2";
}
elseif (errorCondition3)
{
    echo "Error condition 3";
}
elseif (errorCondition4)
{
    echo "Error condition 4";
}
else
{
    //Perform actions for success scenario
}
Edited by Psycho
  • Like 1
Link to comment
Share on other sites

I completely agree with Psyco in most cases but if your typing mostly the same output you'll want to nest

 

I have a general rule of of nesting at max is 3 if i go over i check if i can do the logic differently.

 

Basically the flip side of the coin

if(!isset($_POST["submit"])){// if there was no submit variable passed to the script (i.e. user has visited the page without clicking submit), display the form:
    if(!empty($_SESSION["MSG"])){echo '<div class="MSG">' . $_SESSION["MSG"] . '</div><br /><br />';}//easyer to nest this
    echo '<form name="LoginForm" class="formbox" id="LoginForm" action="index.php" method="post" />
    Username: <input type="text" name="username" id="username"/><br />
    Password: <input type="password" name="password"><br />
    <input type="submit" name="submit" id="submit" value="submit" />
    </form>';
    unset($_SESSION["MSG"]);

}//elseif do more stuff

VS

if(!isset($_POST["submit"]) && !empty($_SESSION["MSG"])){//There was a session message and if there was no submit variable passed to the script (i.e. user has visited the page without clicking submit), display the form:
    echo '<div class="MSG">' . $_SESSION["MSG"] . '</div><br /><br />';
    echo '<form name="LoginForm" class="formbox" id="LoginForm" action="index.php" method="post" />
    Username: <input type="text" name="username" id="username"/><br />
    Password: <input type="password" name="password"><br />
    <input type="submit" name="submit" id="submit" value="submit" />
    </form>';
    unset($_SESSION["MSG"]);

}elseif(!isset($_POST["submit"])){// if there was no submit variable passed to the script (i.e. user has visited the page without clicking submit), display the form:
    echo '<form name="LoginForm" class="formbox" id="LoginForm" action="index.php" method="post" />
    Username: <input type="text" name="username" id="username"/><br />
    Password: <input type="password" name="password"><br />
    <input type="submit" name="submit" id="submit" value="submit" />
    </form>';

}//elseif do more stuff
Edited by Werezwolf
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.