Php switch statement

Php switch statements to replace complicated if-elseif statements. Switch statements compare an expression against all of the possible entries inside their body. If they don’t find an exact match, the program will run the “default” clause and ignore the rest of the statement. In PHP, you may use a “break” statement to terminate the code’s execution and pass the control to the succeeding scripts.

Syntax:-


<?php
switch (expression) {
case expression:
statement1
case expression:
statement2
...
default:
statementn
}
?>

Example:-


<?php
$game = "Cricket";
switch ($game) {
  case "Cricket":
    echo "Sachin belongs to cricket!";
    break;
  case "Hockey":
    echo "Dhayan Chand belongs to Hockey";
    break;
  case "Tennis":
    echo "Mahesh Bhupathi belongs to Tennis!";
    break;
  default:
    echo "Players neither belongs to Cricket, Hockey, nor Tennis!";
}
?>
Output:- Sachin belongs to cricket!

Try it Yourself

Php switch statement – Interview Questions

Q 1: What is a switch statement?
Ans: It selects one block of code to execute from multiple choices.
Q 2: Why use switch instead of if-else?
Ans: It improves readability for multiple conditions.
Q 3: What is the role of break in switch?
Ans: It stops further case execution.
Q 4: What is the default case?
Ans: It executes when no case matches.
Q 5: Can switch use strings?
Ans: Yes.

Php switch statement – Objective Questions (MCQs)

Q1. Switch statement is used to ______.






Q2. Which keyword is used to mark the end of a case block?






Q3. Which keyword defines the default block in switch?






Q4. Can multiple cases execute the same code block without break?






Q5. Switch expression is evaluated ______.






Related C# Dictionary Topics