PHP Velho Oeste 2024

if

if문은 PHP를 포함해서 모든 언어에 있어서 가장 중요한 기능 중 하나이다. 이 제어문으로 각각 다른 코드에 대해 조건적인 수행을 가능케한다. if문의 기능은 C와 비슷하다:

if (expr)
    statement

표현식에 관한 섹션에서 설명된것처럼 expr은 논리(Boolean)값으로 취급된다. exprTRUE와 같다면 PHP는 statement를 수행할것이고, FALSE라면 무시될것이다. 무슨값이 FALSE인지 알려면 '논리값으로 변환하기' 섹션을 참고한다.

다음 예는 $a$b보다 크다면 a는 b보다 크다를 출력할 것이다.

<?php
if ($a $b)
    echo 
"a는 b보다 크다";
?>

종종 하나 이상의 구문을 조건적으로 수행시켜야 하는 때가 있다. 물론 if절로 각 구문을 감싸줄 필요는 없다. 대신, 구문 그룹안에 몇개의 구문을 그룹화할 수 있다. 예를 들면, 이코드는 $a$b보다 크다면 a는 b보다 크다라고 출력할것이고, $a의 값을 $b로 지정하게 될것이다.

<?php
if ($a $b) {
    echo 
"a는 b보다 크다";
    
$b $a;
}
?>

If문은 다른 if문안에 무한정으로 내포될수 있다. 이와 같은 기능은 프로그램의 여러부분을 조건적으로 수행하기 위한 유연성을 제공한다.

add a note add a note

User Contributed Notes 4 notes

up
170
robk
10 years ago
easy way to execute conditional html / javascript / css / other language code with php if else:

<?php if (condition): ?>

html code to run if condition is true

<?php else: ?>

html code to run if condition is false

<?php endif ?>
up
34
techguy14 at gmail dot com
13 years ago
You can have 'nested' if statements withing a single if statement, using additional parenthesis.
For example, instead of having:

<?php
if( $a == 1 || $a == 2 ) {
    if(
$b == 3 || $b == 4 ) {
        if(
$c == 5 || $ d == 6 ) {
            
//Do something here.
       
}
    }
}
?>

You could just simply do this:

<?php
if( ($a==1 || $a==2) && ($b==3 || $b==4) && ($c==5 || $c==6) ) {
   
//do that something here.
}
?>

Hope this helps!
up
27
Christian L.
13 years ago
An other way for controls is the ternary operator (see Comparison Operators) that can be used as follows:

<?php
$v
= 1;

$r = (1 == $v) ? 'Yes' : 'No'; // $r is set to 'Yes'
$r = (3 == $v) ? 'Yes' : 'No'; // $r is set to 'No'

echo (1 == $v) ? 'Yes' : 'No'; // 'Yes' will be printed

// and since PHP 5.3
$v = 'My Value';
$r = ($v) ?: 'No Value'; // $r is set to 'My Value' because $v is evaluated to TRUE

$v = '';
echo (
$v) ?: 'No Value'; // 'No Value' will be printed because $v is evaluated to FALSE
?>

Parentheses can be left out in all examples above.
up
25
grawity at gmail dot com
16 years ago
re: #80305

Again useful for newbies:

if you need to compare a variable with a value, instead of doing

<?php
if ($foo == 3) bar();
?>

do

<?php
if (3 == $foo) bar();
?>

this way, if you forget a =, it will become

<?php
if (3 = $foo) bar();
?>

and PHP will report an error.
To Top