Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semi-colon after a case valid in a PHP switch statement?

Tags:

syntax

php

I'm debugging some code for a client and found the following syntax:

switch ($i) {
    case 0;
        echo "i equals 0";
        break;
    case 1;
        echo "i equals 1";
        break;
    case 2;
        echo "i equals 2";
        break;
}

The case statements end in semi-colons rather than colons. Turns out this does compile, but is it legit? I've never seen that syntax before.

like image 314
Yarin Avatar asked Feb 13 '12 19:02

Yarin


People also ask

Does PHP use semicolons?

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block.

Can we use condition in switch case PHP?

PHP doesn't support this syntax. Only scalar values allowed for cases.

Why is colon used in PHP?

In PHP, the double colon :: is defined as Scope Resolution Operator. It used when when we want to access constants, properties and methods defined at class level. When referring to these items outside class definition, name of class is used along with scope resolution operator.

What is the use of switch case in PHP?

What Is the Use of the Switch Statement? In PHP, the switch statement is considered as an alternative to if-elseif-else statements. More often than not, you want to compare a variable with different values, and based on that you want to execute a piece of code.


1 Answers

From the documentation:

It's possible to use a semicolon instead of a colon after a case like:

switch($beer)
{
    case 'tuborg';
    case 'carlsberg';
    case 'heineken';
        echo 'Good choice';
    break;
    default;
        echo 'Please make a new selection...';
    break;
}
like image 91
thetaiko Avatar answered Oct 16 '22 10:10

thetaiko