PHP Velho Oeste 2024

제어 구조의 대체 문법

PHP는 제어 구조를 위해 대체 문법을 제공한다; 즉 if, while, for, foreach, 그리고 switch. 각 경우에 대체 문법의 기본형태는 괄호열기를 콜른 (:)으로 대체하고 괄호닫기는 각각 endif;, endwhile;, endfor;, endforeach;, 또는 endswitch;으로 대체한다.

<?php if ($a == 5): ?>
A는 5와 같다
<?php endif; ?>

위 예에서는 대체 문법으로 쓰여진 if구문안에 "A는 5와 같다" HTML 블록이 포함되어있다. 이 HTML 블록은 $a가 5와 같을때만 출력될것이다.

대체 문법은 elseelseif문에도 적용이 된다. 다음은 elseifelse문 과 같이 있는 if문 절의 대체 형태이다:

<?php
if ($a == 5):
    echo 
"a는 5와 같다";
    echo 
"...";
elseif (
$a == 6):
    echo 
"a는 6과 같다";
    echo 
"!!!";
else:
    echo 
"a는 5도 아니고 6도 아니다";
endif;
?>

더 많은 예는while, forif섹션에 있다.

add a note add a note

User Contributed Notes 1 note

up
20
toxyy
2 years ago
I feel compelled to give a more elegant way using heredoc than the other comment:

<ul>
<?php foreach($list as $item): echo
<<<ITEM
    <li id="itm-$item[number]">Item $item[name]</li>
ITEM;
endforeach;
?>
</ul>

Which works better with multi line blocks, as you only need one overall php tag.

(please don't omit the closing </li> tag despite it being legal, personal preference)
To Top