Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: two values in the case of Switch?

If "car" or "ferrari" as an input, it should print "car or ferrari". How can I achieve it?

<?php
$car ='333';
switch($car)
{

        case car OR ferrari:
                print("car or ferrari");
                break;
        case cat:
                print("cat");
                break;
        default:
                print("default");
                break;
}
?>
like image 902
hhh Avatar asked Sep 05 '09 16:09

hhh


1 Answers

Use two case clauses:

case 'car':
case 'ferrari':
    print("car or ferrari");
    break;

The explanation:

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.

like image 183
Gumbo Avatar answered Oct 16 '22 11:10

Gumbo