Case and Switch Statement
In the event that a nested If..Then..Else statement becomes complex, a case statement migh just be a better solution. In PHP, the condition is evaluated only once and the expression can only evaluate to a simple data type. http://www.php.net/manual/en/control-structures.switch.php
Example
To post a parcel, the cost is calculated by multiplying the weigh by a rate that depends on the weight. The more the parcel weighs, the greater the rate. For parcels less than 2 kg, the rate is 3.5. For parcels less than 5 kg, the rate is 5.5. Otherwise the rate is 6.5.
<?php
//Calculating parcel freight cost in PHP and designed for use at the command line
fwrite(STDOUT, "Parcel freight cost calculator. \n");
fwrite(STDOUT, "Enter the weight of the parcel -> ");
fscanf(STDIN, "%d\n", $weight);
Switch ($weight) {
case 0:
case 1:
$rate = 3.5;
break;
case 2:
case 3:
case 4:
$rate = 5.5;
break;
default:
$rate = 6.5;
}
$cost = $rate * $weight
fwrite(STDOUT, "The cost to send the parcel is $".$cost."\n");
exit(0);
?>
Note: Any value entered is rounded down to the nearest whole number for comparison.
Exercises
-
Write a program that will display one if 6 different witty comments based on the results of a numbers from 1 to 6 entered by the user.
-
Please add another example
-
Please add another example
Example 2 - Switch also works with Characters and Strings:
This example also has a switch within a switch. Also, there is a a variable $error to monitor whether or not to do the last printout.
<?php
//Displaying text based on string input in PHP and designed for use at the command line
fwrite(STDOUT, "Display the Hexadecimal value of the colours of the rainbow (ROYGBIV) \n\n");
fwrite(STDOUT, "Enter a colour of the rainbow -> ");
fscanf(STDIN, "%s\n\n", $colour);
$error = 0;
Switch ($colour) {
case 'red':
fwrite(STDOUT, "Thats going to be quite a bright red you know. \n");
$hex = '#FF0000';
break;
case 'orange':
fwrite(STDOUT, "There is quite a few colours of orange \n ");
fwrite(STDOUT, "Choose one of the following: \n ");
fwrite(STDOUT, "Orange \n ");
fwrite(STDOUT, "Darkorange \n ");
fwrite(STDOUT, "Orangered \n\n --> ");
fscanf(STDIN, "%s\n\n", $colour);
Switch ($colour) {
case 'orange':
$hex = '#FF9900';
break;
case 'darkorange':
$hex = '#FF9900';
break;
case 'orangered':
$hex = '#FF3300';
break;
default:
fwrite(STDOUT, "There are all types of orange... I dont know that one \n");
$error = 1;
}
break;
case 'yellow':
$hex = '#FFFF00';
break;
case 'green':
$hex = '#009900';
break;
case 'blue':
$hex = '#0000FF';
break;
case 'indigo':
$hex = '#330099';
break;
case 'violet':
$hex = '#FF99FF';
break;
default:
fwrite(STDOUT, "I dont know that one \n");
$error = 1;
}
if ($error != 1)
{
fwrite(STDOUT, "The Hexidecimal value of " .$colour. ' is ' .$hex. "\n\n");//note multiple \n's create multiple blank lines.
}
exit(0);
?>
Screen Shot 1 of above

Screen Shot 2 of above

Comments (0)
You don't have permission to comment on this page.