Skip to main content

PHP Switch Statement

By SamK
0
0 recommends
Topic(s)

The switch statement is used to perform different actions depending on the value of a specific condition.

The switch statement basically chooses one of many blocks of code and executes it.

Syntax

<?php
switch (expression) {
  case option1:
    // Execute this block for option 1;
    break;
  case option2:
    // Execute this block for option 2;
    break;
  case option3:
     // Execute this block for option 3;
     break;
  default:
     // Execute this block if no case matches;
}
?>

Here’s how it works:

  • The expression is evaluated once.
  • The value of the expression is compared with the value of each case.
  • If a match is found, the corresponding block of code is executed.
  • The break keyword exits the switch block.
  • If there is no match, the default code block is executed.

Example:

<?php
$favoriteFruit = "apple";

switch ($favoriteFruit) {
  case "apple":
    echo "I love apples!";
    break;
  case "blueberry":
    echo "I enjoy blueberries!";
    break;
  case "kiwi":
    echo "Kiwis are my favorite!";
    break;
  default:
    echo "My favorite fruit isn't apple, blueberry, or kiwi!";
}
?>

/*
Output:
I love apples!
*/

The break Keyword

  • When PHP encounters a break keyword, it exits the switch block. 
  • This halts the execution of any subsequent code, and no additional cases are evaluated. 
  • The final case block does not require a break statement, as execution automatically ends there.

Warning: If you skip the break statement in a case that is not the last one, and that case evaluates as true, the following case will also execute, regardless of whether its condition matches.

The default Keyword

The default keyword specifies the code to execute if no other case matches the given expression.

Example:

<?php
$dayNumber = 3;

switch ($dayNumber) {
  case 7:
    echo "Today is Saturday!";
    reak;
  case 0:
      echo "Today is Sunday!";
      break;
  default:
      echo "I can't wait for the weekend to arrive!";
}
?>

/*
Output:
I can't wait for the weekend to arrive!
*/

The default case is not required to be the last case in a switch block.

While placing the default block elsewhere in the switch block is allowed, it is not recommended.

Note: If the default case is not the last block in the switch statement, ensure to conclude the default block with a break statement.

Common Code Blocks

To have multiple cases share the same code block, you can specify them like this:

Example:

<?php
$dayNumber = 3;

switch ($dayNumber) {
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:  
    echo "Weekdays can be challenging!";
    break;
  case 6:
  case 0:
    echo "Weekends are always enjoyable!";
    break;
  default:
    echo "Oops! Something went wrong.";
}
?>

/*
Output:
Weekdays can be challenging!
*/

Questions & Answers