简体   繁体   中英

switch case not working correctly

I try to case value inside switch. According to this code, it should be echo "Your favorite color is red", but it doesn't. When I run this code, it give a result:

Your favorite color is neither red, blue, nor green! but red colour.

Here is my code

<?php
$response = null;

switch ($msg) {
    case "red":
        echo "Your favorite color is red";
        break;
    case "blue":
        echo "Your favorite color is blue!";
        break;
    case "green":
        echo "Your favorite color is green!";
        break;
    default:
        echo "Your favorite color is neither red, blue, nor green! but " . $msg . " colour.";
}

To mark this as answered, as suggested in my comment, you need to validate your input to ensure that no white spaces are throwing off your switch statement, to do so you can use trim .

Another suggestion would be to use isset and empty on your incoming $_POST too to ensure that it is being sent. You should always sanitize your user input too as someone could be passing malicious data through your request. In your current instance they wouldn't be able to do much lasting damage but when working on larger projects it is extremely important to validate and sanitize any incoming data. Never trust user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM