0

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.";
}
7
  • Then check your $msg value; problem with $msg and thats why gives you a default value. Commented Jun 5, 2018 at 3:44
  • my $msg value is red. I have tried to echo it.
    – Kevin
    Commented Jun 5, 2018 at 3:45
  • Does $msg have any whitespace that needs to be trimmed? Try echo $msg === 'red'
    – jspcal
    Commented Jun 5, 2018 at 3:48
  • Please ensure the value ($msg) is exactly as it is in the case by using trim and validate it with isset and empty.
    – Script47
    Commented Jun 5, 2018 at 3:48
  • Please don't modify the code in your OP, as it invalidates any advice that has been given, instead edit it and add on to your post.
    – Script47
    Commented Jun 5, 2018 at 3:52

1 Answer 1

1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.