downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

제어 구조의 대체 문법> <else
Last updated: Fri, 24 Jul 2009

view this page in

elseif/else if

elseif, 이 이름에서 알수 있듯이, ifelse의 조합이다. else처럼 이 구문은 if절 다음에 와서 원래 if표현식이 FALSE와 같은 경우에 다른 구문을 수행한다. 그러나, else와는 달리 elseif조건 표현식이 TRUE일 때만 대체 표현식을 수행할것이다. 예를 들면 다음 코드는 a는 b보다 크다, a는 b와 같다a는 b보다 작다을 출력할것이다.

<?php
if ($a $b) {
    echo 
"a는 b보다 크다";
} elseif (
$a == $b) {
    echo 
"a는 b와 같다";
} else {
    echo 
"a는 b보다 작다";
}
?>

같은 if절 안에 몇개의 elseif절이 존재할수 있다. 가장 먼저 TRUE가 되는 elseif표현식이 수행될것이다. PHP에서는 'else if' (두 단어)로 쓸수 있고 'elseif' (한 단어) 와 방식은 같다. 문장적(syntactic)으로는 다르다 (C에 익숙하다면, 이것은 같은 방식이다) 그러나 그 둘 모두 완전히 같은 결과를 보여줄것이다.

elseif절은 선행 if 표현식과 다른 elseif표현식이 FALSE이고, 이 elseif표현식이 TRUE일때만 수행된다.

Note: elseifelse if은 위 예제처럼 대괄호를 사용할 때 정확히 같은 구문으로 간주됩니다. if/elseif 조건을 콜론을 사용해서 정의할 때, else if 처럼 두 단어로 나눠서는 안됩니다. PHP는 처리 오류로 실패합니다.

<?php

/* 부적합한 방법: */
if($a $b):
    echo 
$a." is greater than ".$b;
else if(
$a == $b): // 컴파일 되지 않습니다.
    
echo "위 줄은 처리 오류를 일으킵니다.";
endif;


/* 적합한 방법: */
if($a $b):
    echo 
$a." is greater than ".$b;
elseif(
$a == $b): // 단어가 붙어 있는 점에 주의.
    
echo $a." equals ".$b;
else:
    echo 
$a." is neither greater than or equal to ".$b;
endif;

?>



add a note add a note User Contributed Notes
elseif/else if
31-Jan-2007 10:54
There is no good way to interpret the dangling else.  One must pick a way and apply rules based on that. 

Since there is no endif before an else, there is no easy way for PHP to know what you mean.
Vladimir Kornea
27-Dec-2006 05:59
The parser doesn't handle mixing alternative if syntaxes as reasonably as possible.

The following is illegal (as it should be):

<?
if($a):
    echo
$a;
else {
    echo
$c;
}
?>

This is also illegal (as it should be):

<?
if($a) {
    echo
$a;
}
else:
    echo
$c;
endif;
?>

But since the two alternative if syntaxes are not interchangeable, it's reasonable to expect that the parser wouldn't try matching else statements using one style to if statement using the alternative style. In other words, one would expect that this would work:

<?
if($a):
    echo
$a;
    if(
$b) {
      echo
$b;
    }
else:
    echo
$c;
endif;
?>

Instead of concluding that the else statement was intended to match the if($b) statement (and erroring out), the parser could match the else statement to the if($a) statement, which shares its syntax.

While it's understandable that the PHP developers don't consider this a bug, or don't consider it a bug worth their time, jsimlo was right to point out that mixing alternative if syntaxes might lead to unexpected results.

제어 구조의 대체 문법> <else
Last updated: Fri, 24 Jul 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites