PHP – Switch

PHP – Switch

 

The PHP switch statement (native function) executes a different piece of code depending on the value of a variable (or expression).

Here is a simplified version of the PHP switch syntax:

PHP

switch (expression) {
    case value_1:
        // case expression = value_1
        break;

    case value_2:
        // case expression = value_2
        break;

    case value_3:
        // case expression = value_3
        break;
    ...

    default:
        // default code to be executed if none of the above cases are met
}

PHP switch example

The switch statement is quite simple. It evaluates the expression or variable once, and then it compares the value to one of the given cases. If no match is found, then the default case is executed. Use break after every block of code to prevent code form continuing.

Here is a real example of using the PHP switch statemented

PHP

<?php
$role = "editor";

switch ($role) {
    case "admin":
        echo "Hello master. You can manage users and edit their content.";
        break;

    case "editor":
         echo "As an editor, your job is very important to us. You can manage your profile and create, edit and publish your own content.";
        break;

    case "customer":
         echo "Thank you for registering. You have now access to all our content. Enjoy reading";
        break;

    default:
         echo "Your are an anonymous visitor. Please register to have access to cool stuff";
}
?>

This will simply print the following line

As an editor, your job is very important to us. You can manage your profile and create, edit and publish your own content.

There are times when you want to execute the same block of code for multiple cases. This is how you group case for the PHP switch statement.

PHP

<?php
$role = " publisher_team ";

switch ($role) {
    case "administration_geek":
    case "moderation_board":
    case "marketing_department":
        echo "Case administrator, moderator and marketing";
        break;

    case "editor_stuff":
    case "publisher_team":
         echo "Case editor and publisher";
        break;

    case "paying_customers":
    case "registered_users":
         echo "Case customer and users";
        break;

    default:
         echo "Undefined role will execute this code";
}
?>

This will simply print the following line

Case editor and publisher

The PHP switch alternative syntax

There is no switch shorthand like the if statement for example but there is instead an alternative for the above syntax.

PHP

<?php
$role = "editor";

switch ($role):
    case "admin":
        echo "I am the one that knows your browser history";
        break;

    case "editor":
        echo "I edit stuff";
        break;

    case "customer":
        echo "I both things";
        break;

    default:
        echo "Nobody is perfect. I am nobody";

endswitch;
?>

On the PHP manual page there is a notice that you can not insert a space or line-break between the “switch ($role):” and “case “admin”:”. This will trigger a warning

PHP
Parse error: syntax error, unexpected T_INLINE_HTML, expecting T_ENDSWITCH or T_CASE or T_DEFAULT

In other words this will not be correct:

PHP

<div>
<?php switch($role): ?>
    <?php case "admin": ?>
        <div>This switch syntax is not correct</div>
        <?php break;?>
    <?php case "editor": ?>
        </div>This way of using switch will trow a syntax error<div>
        <?php break;?>
<?php endswitch;?>
</div>

Although this PHP switch code seems perfectly valid, there is a line-break after this . Remember that when you close the PHP code, The HTML comes in, and that line-break is interpreted as a “rn” or carriage return.

Mixing statements

Although for some it may seem obvious, I would like to mention that, like any other statement, you can mix the switch statement with any other statements. For example, you can place a second switch inside it, an if, a do-while or any other complex piece of code. On the other hand is not always a good idea place to much code inside a switch statement. It is a good practice to stay simple and use a separate function or build an object if you have to place a lot of code inside a switch.

PHP

<?php
$role       = "administration";
$action     = true;
$came_from  = "home_page";

switch ($role) {
    case "administration":
        if($action): 
            # do some cool things
        else:
            # do some other awesome things
        endif;

        break;

    case "paying_customers":
    case "registered_users":
         say_hello();
        break;

    default:
        
        # Undefined role will execute this code
        switch ($came_from) {
            case "home_page":
                echo "You think our home page is cool?";
                break;

            case "article_page":
                echo "Did you liked the previous article?";
                break;

            default:
            # if none of the above, it means it comes from organic search 
            echo "Hmm...Is this what you were looking for in the first place?";
        }
}

/*
 * This function will get all user info from database (for example)
 */
function say_hello(){
    echo "Hi there $name!!";
    # a lot of code here
}

?>

Take a closer look to the above switch syntax and try to understand it. It is a good idea to practice a little bit before continuing to the next tutorial. See you on the next page.

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.  

Google –> SETScholars