Skip to content

PHP Switch Statement: 7 Case and Code Examples

PHP Switch Statement: 7 Case and Code Examples

Switch statement is used to execute one statement from multiple conditions in PHP. It works like PHP if-else-if statement. But it's better that if-else-if statement.

Syntax for Switch statement in php:

switch(condiction){      
case value1:      
 //code to be executed  
 break;  
case value2:      
 //code to be executed  
 break;  
......      
......
......
default:       
 code to be executed if all cases are not matched;    
}  

PHP Switch Example

$num = 30;    
switch($num){    
case 10:    
echo("your submited number is equals to 10");    
break;    
case 20:    
echo("your submited number is equal to 20");    
break;    
case 30:    
echo("your submited number is equal to 30");    
break;    
default:    
echo("number is not equal to 10, 20 or 30");    
}   

Output:

your submited number is equal to 30

What Is a PHP Switch Statement?

When Switch Is Useful

A PHP switch statement compares one expression with several possible values and runs the matching branch. It is useful when one variable, such as a status, role, menu choice, or numeric option, determines which action should occur.

Switch can make a long series of comparisons easier to scan. It is not automatically better than if and elseif; choose the structure that makes the condition and its expected result easiest to understand.

PHP switch and match comparison
PHP switch or match?

Switch Compared with if and elseif

An if chain is usually clearer when every branch has a different condition. Switch is a natural fit when one expression is compared with a list of alternatives. PHP evaluates the switch expression once and then checks the case values.

PHP Switch Statement Syntax

Expression, case, break, and default

The general structure looks like this:

switch ($value) {
  case 'first':
    // code for the first value
    break;
  case 'second':
    // code for the second value
    break;
  default:
    // code when nothing matches
}

The expression after switch is compared with each case. The break statement stops execution after the matching branch. The default branch is optional, but it is valuable when input can contain an unexpected value.

Writing a Readable Switch Block

Indent each case consistently and keep the branch work short. If a branch needs many unrelated operations, call a descriptive function rather than turning the switch block into a large procedure.

Basic PHP Switch Example

Matching a Number

Here is a corrected version of a numeric example:

$number = 30;

switch ($number) {
  case 10:
    echo 'The number is 10';
    break;
  case 20:
    echo 'The number is 20';
    break;
  case 30:
    echo 'The number is 30';
    break;
  default:
    echo 'The number is not 10, 20, or 30';
}

Reading the Output

Because the value of $number is 30, PHP enters the case labeled 30, prints its message, and stops at break. It does not continue into default.

Using String Values in Switch Cases

Matching a Status or Role

String cases are useful for values received from a form, a database, or an application state:

$status = 'published';

switch ($status) {
  case 'draft':
    echo 'Show the editor';
    break;
  case 'published':
    echo 'Show the public article';
    break;
  case 'archived':
    echo 'Show the archive message';
    break;
  default:
    echo 'Unknown status';
}

Handling Unexpected Input

Do not assume that external input always matches the values you designed. Normalize values where appropriate, validate them before the switch, and use default to provide a safe fallback. A default branch can log an unexpected state, return an error, or display a neutral message.

Why the break Statement Matters

Preventing Accidental Fall-Through

Without break, PHP continues executing statements in the following case blocks after it finds a match. This is called fall-through. It may produce multiple outputs when you expected only one.

$level = 1;
switch ($level) {
  case 1:
    echo 'Basic';
  case 2:
    echo 'Advanced';
}

For level 1, both messages can run because there is no break after the first branch. Add break when the branches represent separate alternatives.

When Fall-Through Is Intentional

Fall-through can group values that share an outcome, but make the intention obvious. A cleaner grouped pattern is to place consecutive cases together and put the shared code after the last case:

$format = 'jpg';
switch ($format) {
  case 'jpg':
  case 'png':
  case 'gif':
    echo 'Raster image';
    break;
  default:
    echo 'Other format';
}

Using the default Case

Providing a Fallback Result

The default branch runs when no case value matches. Put it at the end by convention, even though PHP can technically recognize it elsewhere in the block.

$option = 'unknown';
switch ($option) {
  case 'compact':
    echo 'Compact layout';
    break;
  case 'wide':
    echo 'Wide layout';
    break;
  default:
    echo 'Use the standard layout';
}

Validating Unknown Values

For input that controls permissions, prices, file types, or database operations, a fallback should not silently perform a dangerous action. Reject invalid values or return a controlled error when the input is not recognized.

Grouping Multiple Cases

Sharing One Code Block

Several cases can lead to one branch. This is useful when different labels represent the same broad behavior:

$day = 'Saturday';
switch ($day) {
  case 'Saturday':
  case 'Sunday':
    echo 'Weekend';
    break;
  default:
    echo 'Weekday';
}

Keep grouped cases genuinely related. If each value needs a slightly different explanation or side effect, separate the branches instead of hiding differences in a long shared section.

Switch with Conditions Using switch(true)

When Condition-Based Matching Helps

Some developers use switch (true) when each case contains a Boolean condition:

$score = 82;
switch (true) {
  case $score >= 90:
    echo 'A';
    break;
  case $score >= 75:
    echo 'B';
    break;
  default:
    echo 'C or below';
}

When if and elseif Are Easier

This pattern can work, but an if and elseif chain is often more immediately understandable for ranges and complex conditions. Use the form your team can read and test most confidently.

PHP Switch Comparison Behavior

Understanding Loose Comparison

Traditional PHP switch and case comparisons use loose comparison behavior. Values that look different in type may still be considered equal after PHP's comparison rules are applied. This can surprise developers when input arrives as a string but is compared with a number.

Normalizing Input Before Matching

Validate and normalize data before the switch when its type matters. Convert an expected numeric value deliberately, check that it is within the allowed range, or use a structure that makes strict comparison requirements clearer.

Switch Versus the PHP match Expression

Important Differences

Modern PHP also provides the match expression. It returns a value, uses strict comparison, and does not require the same fall-through style as switch. It can be a good choice when a value must be selected directly from a small set of exact alternatives.

$label = match ($status) {
  'draft' => 'Editing',
  'published' => 'Live',
  default => 'Unknown',
};

Choosing the Appropriate Construct

Use switch when statement-oriented branches and grouped cases make the intent clear. Use match when strict value mapping and an expression result are more useful. Confirm the PHP version supported by your project before using newer syntax.

Common PHP Switch Mistakes

Missing break and Incorrect Case Syntax

Common problems include misspelling the switch expression, forgetting a colon after case, omitting break accidentally, and placing unrelated code in a branch. Review the syntax carefully and test both matching and non-matching inputs.

Forgetting a Default Branch

If no case matches and there is no default, the switch performs no branch action. That may be correct in a tightly controlled situation, but external input usually deserves an explicit fallback.

  • Use a meaningful expression.
  • Keep case labels easy to compare.
  • Add break unless fall-through is deliberate.
  • Use default for unexpected values.
  • Normalize input before matching.
  • Test every case and the fallback.

FAQ

What is a switch statement in PHP?

It compares one expression with several case values and runs the branch that matches. It is useful for multiple alternatives based on the same value.

Why is break used in a PHP switch statement?

Break stops execution after a matching branch. Without it, PHP may continue into the next case and produce unintended fall-through.

What happens if no PHP switch case matches?

If a default branch exists, it runs. If there is no default, no switch branch is executed.

Can a PHP switch statement use strings?

Yes. Cases can contain strings such as draft, published, admin, or guest. Validate external values before using them.

Should I use switch or match in PHP?

Use switch for statement branches and grouped alternatives. Use match when strict comparisons and a returned value make the code clearer, provided your supported PHP version includes it.

Conclusion

The PHP switch statement is a readable way to choose between several outcomes based on one expression. A reliable block uses clear case labels, deliberate break statements, and a useful default branch.

For maintainable PHP, test every expected value, handle unexpected input safely, and choose between switch, if and elseif, and match according to the conditions and PHP version your project supports.

Testing a Switch Block

Test Every Branch

Run the code with each expected case, an unexpected value, an empty value where relevant, and a value with the wrong type. This reveals missing breaks, incorrect assumptions about input, and fallback behavior that was never tested.

Keep Business Rules Separate

When a case needs database access, authorization, or several unrelated operations, move that work into a named function or service. The switch should make the decision visible while the called code handles the detailed work.

Write a comment