Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!