12. 장. 제어 구조 (Control Structures)

차례
if
else
elseif
제어구조의 다른 표현 (Alternative syntax for control structures)
while
do..while
for
foreach
break
continue
switch
require()
include()
require_once()
include_once()

모든 PHP 스크립트는 일련의 구문으로 이루어 진다. 하나의 구문은 대입문이 될 수도 있고, 함수 호출, 반복문, 조건문이 될 수도 있으며 심지어는 아무 내용이 없는 빈 문장일 수도 있다. 한 구문은 일반적으로 세미콜론(;)으로 끝난다. 또한 여러개의 구문을 중괄호({,})를 사용하여 하나의 그룹으로 만들어 사용할 수도 있다. 이 구문-그룹은 그 그룹의 모든 구문들이 하나의 구문인 것처럼 인식된다. 여기서는 여러 가지 구문형태에 대해 알아본다.

if

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP의 if 문은 C와 비슷하다.:

if (expr)
    statement

As described in the section about expressions, expr is evaluated to its truth value. If expr evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.

The following example would display a is bigger than b if $a is bigger than $b:

if ($a > $b)
    print "a is bigger than b";

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

if ($a > $b) {
    print "a is bigger than b";
    $b = $a;
}

If statements can be nested indefinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.