PHP & MySQL, Tutorials

From time to time you may need to find a value of a variable to perform an action you can do this with an if elseif else statement but its much more efficient to use a switch statement to do the same thing.

Using a switch statement means less code and easier to read.

In this example I have created a variable called $mydata which contains a value of 2 using the assignment operator.

$mydata = 2;

Then I start the switch statement using switch() for switch to work it needs a variable parameter in this case am using $mydata then open a curly bracket.

switch( $mydata ) {

Then the switch statement looks for different cases to see which one is true. If a one of the cases is true then the code is executed for that case in this case the value if $mydate is 2 for case 2 is true and the echo statement is executed.

Each case statement needs a break to tell php to end the case and move to the next one.

<?php
case 0:
     echo "mydata equals 0";
     break;
case 1:
     echo "mydata equals 1";
     break;
case 2:
     echo "mydata equals 2";
     break;
?>

If none of the cases match true then you can set an optional default which will be exectuted if none of the cases are true. So for this example if $mydata does not have a value of either 0,1 or 2 then all the cases fail and the default is executed. Then the using the closing bracket to close the switch statement. 

<?php
default:
    echo "mydata is not equal to 0, 1 or 2";
}
?>

Here's the full script: 

<?php

//define a variable with a value of 2
$mydata = 2;

// using a switch to find the value of $mydata then echo the value or fail if none of the values are found.
switch( $mydata ) {
case 0:
   echo "mydata equals 0";
   break;
case 1:
   echo "mydata equals 1";
   break;
case 2:
   echo "mydata equals 2";
   break;
default:
   echo "mydata is not equal to 0, 1 or 2";
}
?>