Switch statement should be used in the code when you want to evaluate different cases of a given scenario. The switch statement takes a single variable as input and then checks it against all cases we have in our switch statement.
Let's imagine you own a computer retail store. Depending on the product name we want to display the price of that product.
Now, instead writing separate if else statements for each product name, we simple use the PHP switch statement on the product name variable to evaluate which product we want to the display the price for. Let's have look at the example.
PHP Code:<html>
<body>
<?php
//set product name
$product_name = "Processors";
switch ($product_name)
{
case "Video Cards":
echo "Video cards range from $50 to $500";
break;
case "Monitors":
echo "LCD monitors range from $200 to $400";
break;
case "Processors":
echo "Intel processors range from $100 to $1000";
break;
default:
echo "Sorry, we don't carry $product_name in our catalog";
break;
}
?>
</body>
</html>


LinkBack URL
About LinkBacks

Bookmarks