Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Enhancing a Simple PHP Application Integrating Validation Errors Displaying the Error Message

Frank Novello
Frank Novello
19,299 Points

Why not use else if statements if there was an error? Instead of checking if there was an error for each if statement?

thats all.

1 Answer

Because in elseif control structure, only that one if/elseif block gets executed whose condition returns TRUE first.

<?php
    $color = "red";
    if ($color == "black") {
        echo "Color is Black";
    } elseif ($color == "blue") {
        echo "Color is Blue";
    } elseif ($color == "red") {
        echo "Color is Red"; // Only this block will get executed since its condition returns TRUE
    } else {
        echo "Who knows";
    }
?>

Whereas, on Shirts4Mike contact page, we want to run multiple validation tests on the same condition, i.e. $error_message.

<?php
    $color = "red";
    if ($color == "red") {
        echo "I love Red\n";
    }
    if ($color == "red") {
        echo "Red is my favorite color\n";
    }
    if ($color == "red") {
        echo "I'm so Red!";
    }
    // All 3 blocks will get executed since each if condition returns TRUE
?>

Hence it's more wise to use if than elseif since we want to execute multiple blocks of code on the same test condition. As long as !isset($error_message) returns TRUE, we can keep running validation tests on our data.

Hope this helps!