switch

switch문은 내용상 동일한 표현식의 IF문을 나열한 것과 비슷하다. 많은 경우에 한 변수를 여러 다른 값과 비교하여, 두개의 값이 같는냐에 따라 서로 다른 코드들이 수행되기를 원하는 때가 있다. 바로 이런 경우에 switch문이 사용된다.

다음은 동일한 결과를 가져오는 예를 각각 if문과 switch문으로 표현한 것이다. :

if ($i == 0) {
    print "i equals 0";
}
if ($i == 1) {
    print "i equals 1";
}
if ($i == 2) {
    print "i equals 2";
}
 
switch ($i) {
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        break;
    case 2:
        print "i equals 2";
        break;
}

switch문은 문장 단위로 실행된다. switch에 있는 평가식과 일치하는 case문을 찾아 그 이후부터 switch 블럭이 끝날 때의 모든 문장을 실행한다. 따라서 원하는 경우 break로 실행을 중지시킬 필요가 있다. 다음 예를 보자. :

switch ($i) {
    case 0:
        print "i equals 0";
    case 1:
        print "i equals 1";
    case 2:
        print "i equals 2";
}

여기서 $i가 0이면 모든 print문을 실행할 것이다. 만약 $i가 1이면 마지막 두개의 print문을 실행한다. 따라서 각각의 경우에 하나의 print 문만이 실행되기를 원한다면, break문을 잊지 않아야한다.

In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

switch ($i) {
    case 0:
    case 1:
    case 2:
        print "i is less than 3 but not negative";
        break;
    case 3:
        print "i is 3";
}

특별한 case로 default case가 있다. 이것은 다른 어떤 case에도 맞지 않는 경우를 의미한다. 예를 들어 :

switch ($i) {
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        break;
    case 2:
        print "i equals 2";
        break;
    default:
        print "i is not equal to 0, 1 or 2";
}

다른 중요한 점은 case 표현식에는 정수, 실수, 문자열같은 스칼리 타입으로 평가되는 어떤 표현식이와도 된다는 것이다. 배열이나 객체는 스칼리 타입으로 변환시켜 사용하지 않는 한 사용할 수 없다.

switch 문에 대해서도 Alternative syntax가 지원된다. 자세한 내용은 Alternative syntax for control structures를 살펴보자

switch ($i):
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        break;
    case 2:
        print "i equals 2";
        break;
    default:
        print "i is not equal to 0, 1 or 2";
endswitch;