Php switch statement

A switch statement is like a series of if statement. We are comparing a value with many other values.

Pretend we have a script and want to greet our users.

<?php

$user_name = 'adam';

switch( $user_name ) {
    case "dave":
        echo 'Hello Dave.';
        break;
    case "dan":
        echo 'Hello Dan.';
        break;
    case "bill":
        echo 'Hello Bill.';
        break;
    case "adam":
        echo 'Hello Adam.';
        break;
    default:
        echo 'Hello Guest';
        break;
    }
?>

The above example is not the best use for a switch statement, but it gets the point across.

In the past I have used them to read a URL path for information or in functions for processing images based on the file extension.

Read more about the PHP Switch statement.

Tags:

3 Responses to Php switch statement



    Warning: call_user_func() expects parameter 1 to be a valid callback, function 'vision_comment' not found or invalid function name in /home/adamdev/adampatterson.ca/wp-includes/comment-template.php on line 1334

    Warning: call_user_func() expects parameter 1 to be a valid callback, function 'vision_comment' not found or invalid function name in /home/adamdev/adampatterson.ca/wp-includes/comment-template.php on line 1334

    Warning: call_user_func() expects parameter 1 to be a valid callback, function 'vision_comment' not found or invalid function name in /home/adamdev/adampatterson.ca/wp-includes/comment-template.php on line 1334

Leave a Comment