PHP Switch

Hi everyone,

We use the switch statement to select one of many blocks of code to be executed. In switch statement an expression is compared with some values for each case in the structure. If there is a match, the related code-block will then be executed. After the code to be executed don’t forget to put break; to prevent the code from running into the next case automatically. We use default statement when there is no match. The syntax is:

switch (n)

{
case label1:
  // code to be executed if n=label1;
  break;
case label2:
  // code to be executed if n=label2;
  break;
default:
  // code to be executed if n is different from both label1 and label2;
}

Note: to put default portion in the statement is optional, but to do so is highly recommended.

Here is an example about switch statement: 

The output will be Hello! My name is Mehmet. I don’t have to be sorry! 🙂 

<?php
$myname="Mehmet";
switch($myname)
{
case "John":
echo "Hello! My name is John, not Mehmet. I am sorry :(";
break;
case "Mehmet":
echo "Hello! My name is Mehmet. I don't have to be sorry! :)";
break;
default:
echo "Hello! My name is not neither Mehmet nor John!";
}
?>

In this lesson, you have learned Switch statement in PHP. Stay cool and stay connected to learn more!

Leave a Reply

Your email address will not be published. Required fields are marked *