HS Banner
Back
PHP Switch Statement

Author: Guitarman 01/09/2022
Language: PHP
Tags: php switch


Description:

Use the switch statement to select one of many blocks of code to be executed.

Article:

This is how it works: First we have a single expression selected_color (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

$color= '';
switch ($selected_color) {
    case 1:
        $color = 'red';
        break;
    case 2:
        $color = 'black';
        break;
    case 3:
        $color = 'blue';
        break;
    default:
        $color = 'white';
}

Full Source Code:
Example:

<?php
//if the address in your browser is https://yourdomain.com?id=2 then the color is black.

$id = 0;
if (isset($_GET['id'])){
    $id = (int) $_GET['id']; // get id through query string
}

$color= '';
switch ($id) {
    case 1:
        $color = 'red';
        break;
    case 2:
        $color = 'black';
        break;
    case 3:
        $color = 'blue';
        break;
    default:
        $color = 'white';
}
?>


Back
Comments
Add Comment
There are no comments yet.