Jump to content

Switch Statement Error


wilfred_phang
 Share

Recommended Posts

Hi, i tested for the switch statement example on the W3S php site. But i encountered error. <html><body><?phpswitch ($x){case 1: echo "Number 1"; break;case 2: echo "Number 2"; break;case 3: echo "Number 3"; break;default: echo "No number between 1 and 3";}?></body></html>The error message is as below:Notice: Undefined variable: x in C:\wamp\www\W3C\w3c.php on line 7Notice: Undefined variable: x in C:\wamp\www\W3C\w3c.php on line 10Notice: Undefined variable: x in C:\wamp\www\W3C\w3c.php on line 13No number between 1 and 3 Anybody can tell me how to solve this?Thanks!

Link to comment
Share on other sites

The first part of the switch switch ($x) has a variable called $x . This is what is compared against each case value, so if you said that $x was equal to the number 2 then case 2 would run. The problem is that you script need to set $x to be something.You need the code below if you wanted to set $x to be 2

<?php$x = 2;switch ($x){case 1:echo "Number 1";break;case 2:echo "Number 2";break;case 3:echo "Number 3";break;default:echo "No number between 1 and 3";}?>

You can set $x to be anything and the case can be anything you want to match against

<?php$x = "Volvo";switch ($x){case Audi:echo "Audi";break;case Volvo:echo "Volvo";break;case Merc:echo "Mercedes";break;default:echo "None of these cars";}?>

Link to comment
Share on other sites

Why your second example's Audi and Volvo are undefined?
Those should have been quoted, without quotes PHP thinks they are defined constants instead of values.
<?php$x = "Volvo";switch ($x){case 'Audi':echo "Audi";break;case 'Volvo':echo "Volvo";break;case 'Merc':echo "Mercedes";break;default:echo "None of these cars";}?>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...