in ,

PHP switch Statement

PHP switch
PHP switch

In this tutorial, you will learn about PHP switch Statement step by step. So without much to do, let’s get started.


The switch statement is used to perform distinct actions primarily based on different conditions.


The PHP switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch (n) {
  case label1:
    code to be executed if n=label1;
    break;
  case label2:
    code to be executed if n=label2;
    break;
  case label3:
    code to be executed if n=label3;
    break;
    ...
  default:
    code to be executed if n is different from all labels;
}

This is how it works: First we have a single expression n (most often a variable), this is evaluated once. The value of the expression is then in comparison with the values for each case in the structure. If there’s a in shape, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

Example

<!DOCTYPE html>
<html>
<body>

<?php
$favcolor = "red";

switch ($favcolor) {
  case "red":
    echo "Your favorite color is red!";
    break;
  case "blue":
    echo "Your favorite color is blue!";
    break;
  case "green":
    echo "Your favorite color is green!";
    break;
  default:
    echo "Your favorite color is neither red, blue, nor green!";
}
?>
 
</body>
</html>

READ NEXT

PHP Comments

PHP Variables

PHP Variables Scope

PHP echo and print Statements

PHP Data Types


This is about PHP switch Statement, and we hope you have learned something from this tutorial and share your opinion about this tutorial. What do you think about it, and if you think this tutorial will help some of your friends, do share it with them.

salman khan

Written by worldofitech

Leave a Reply

php if else

PHP if…Else…Elseif Statements

php looping

PHP Loops