PHP Switch Syntax from Codeacademy

PHP Switch Syntax from Codeacademy

Here are some examples being explained.

switch can host a number or a variable.
After you write the case statement, switch will check and echo the correct case.

Something simple should be $var = ‘incvice’ switch($var) case: ‘incvice’ : echo ‘ok’; break;

Examples from codeacademy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
    switch (2) {
        case 0:
            echo 'The value is 0';
            break;
        case 1:
            echo 'The value is 1';
            break;
        case 2:
            echo 'The value is 2';
            break;
        default:
            echo "The value isn't 0, 1 or 2";
    }
    ?>
2
3
4
5
6
7
8
9
10
11
    <?php
    $fruit = "Apple";
 
    switch ($fruit) {
        case 'Apple':
            echo "Yummy.";
            break;
    }
 
    ?>

If you don’t want to use switch, you can just use if / elseif / else. It will do the same thing.

Another example from “All On Your Own!” control switch from php course from codeacademy:

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  <?php
     $var = 'incvice';
 
     switch($var)
        {
            case 'google':
            echo 'google';
            break;
 
            case 'yahoo':
            echo 'yahoo';
            break;
 
            case 'incvice':
            echo 'incvice';
            break;
 
            default:
                echo 'none of the above';
 
        }
    ?>

Remember to add “:” at “case”, instead of ending the row with “;”.

Add a comment: