Sling Academy
Home/PHP/Mastering switch-case statements in PHP

Mastering switch-case statements in PHP

Last updated: January 09, 2024

Introduction

The switch-case statement in PHP is an efficient alternative to lengthy if-else blocks when you need to make a decision based on multiple conditions. If you often find yourself tackling complex conditionals, mastering switch-case might just make your code cleaner and more readable.

Understanding switch-case

The switch-case structure allows a variable to be tested against a series of values, executing different pieces of code depending on which value matches. Here’s a simple switch-case example:

<?php
$color = 'blue';
switch ($color) {
    case 'red':
        echo 'The color is red';
        break;
    case 'green':
        echo 'The color is green';
        break;
    case 'blue':
        echo 'The color is blue';
        break;
    default:
        echo 'Unknown color';
}
?>

This will output The color is blue, because the case matches the value of the $color variable. Remember that without the break keyword, PHP would continue to execute the subsequent case blocks.

Diving Deeper: Cases with Multiple Conditions

Sometimes you might want to match multiple values to a single block of code. This can be cleanly achieved using fall-through:

<?php
$day = 'Saturday';
switch ($day) {
    case 'Saturday':
    case 'Sunday':
        echo 'Weekend vibes!';
        break;
    default:
        echo 'Back to work...';
}
?>

In this case, both Saturday and Sunday will result in the same output: Weekend vibes!

Case-Sensitive String Matching

PHP switch-case statements are case-sensitive by default, which sometimes can be problematic when dealing with user input. To handle this, you can convert the input to a standard case using functions like strtolower() or strtoupper():

<?php
$input = 'YES';

switch (strtolower($input)) {
    case 'yes':
        echo "Let's do this!";
        break;
    case 'no':
        echo "Maybe next time.";
        break;
    default:
        echo 'Invalid input';
}
?>

The example above ensures that ‘YES’, ‘yes’, and even ‘YeS’ all return the positive confirmation output.

Advanced Usage: Switch-case with Arrays

As your applications grow more complex, you might find cases where values you want to switch on are not simple variables, but the result of array operations. For instance:

<?php
$statuses = ['pending', 'failed', 'success'];
$statusKey = 2; // array index representing status

switch ($statuses[$statusKey]) {
    case 'pending':
        echo 'Transaction is pending.';
        break;
    case 'failed':
        echo 'Transaction failed.';
        break;
    case 'success':
        echo 'Transaction succeeded!';
        break;
    default:
        echo 'Invalid transaction status.';
}
?>

In this example, because $statusKey is 2, ‘Transaction succeeded!’ is printed.

Using switch-case in Functions

Switch-case can also be used within functions to return different values based on the input:

<?php
function getServerResponse($code) {
    switch ($code) {
        case 200:
            return 'OK';
        case 404:
            return 'Not Found';
        case 500:
            return 'Internal Server Error';
        default:
            return 'Unknown status code';
    }
}

echo getServerResponse(404); // Outputs: Not Found
?>

Conclusion

The versatility of PHP’s switch-case statement makes it an important tool in your coding toolbox. From simple value matching to advanced functional implementations, the switch-case structure can simplify your decision logic significantly. Apply these examples and tips to your PHP scripts, and you’ll be mastering switch-case statements in no time.

Next Article: Mastering Try-Catch Statements in PHP

Previous Article: Mastering if-else statements in PHP

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array