Javatpoint Logo
Javatpoint Logo

PHP Switch

PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.

Syntax

Important points to be noticed about switch case:

  1. The default is an optional statement. Even it is not important, that default must always be the last statement.
  2. There can be only one default in a switch statement. More than one default may lead to a Fatal error.
  3. Each case can have a break statement, which is used to terminate the sequence of statement.
  4. The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
  5. PHP allows you to use number, character, string, as well as functions in switch expression.
  6. Nesting of switch statements is allowed, but it makes the program more complex and less readable.
  7. You can use semicolon (;) instead of colon (:). It will not generate any error.

PHP Switch Flowchart

php if statement flowchart

PHP Switch Example

Output:

number is equal to 20

PHP switch statement with character

Program to check Vowel and consonant

We will pass a character in switch expression to check whether it is vowel or constant. If the passed character is A, E, I, O, or U, it will be vowel otherwise consonant.

Output:

Given character is vowel

PHP switch statement with String

PHP allows to pass string in switch expression. Let's see the below example of course duration by passing string in switch case statement.

Output:

B.Tech is 4 years course

PHP switch statement is fall-through

PHP switch statement is fall-through. It means it will execute all statements after getting the first match, if break statement is not found.

Output:

Choice c
Choice d
case a, b, c, and d is not found

PHP nested switch statement

Nested switch statement means switch statement inside another switch statement. Sometimes it leads to confusion.

Output:

Hyundai Tucson price is 22.39 - 32.07 L.

Next TopicPHP For Loop




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA