- PHP

Switch and Case for an Array in PHP

Sometimes we may want to create a switch statement for an array.

We can easily do this with switch and, for example, foreach() loop.

Example:

<?php

$array = [
    'dog' => 'Jack',
    'cat' => 'Amy',
    'favoriteDevice' => 'Smartphone',
];

foreach ($array as $key => $value) {
    switch ($key) {
        case 'dog':
            echo "My dog's name is: " . $value . "<br>";
            break;

        case 'cat':
            echo "My cat's name is: " . $value . "<br>";
            break;

        case 'favoriteDevice':
            echo "My favorite device is: " . $value . "<br>";
            break;
    }
}

Output:

My dog’s name is: Jack
My cat’s name is: Amy
My favorite device is: Smartphone