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

search for in the

else> <배열 연산자
Last updated: Sun, 25 Nov 2007

view this page in

제어 구조

Table of Contents

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

if

if문은 PHP를 포함해서 모든 언어에 있어서 가장 중요한 기능(feature) 중 하나이다. 이 제어문으로 각각 다른 코드에 대해 조건적인 수행을 가능케한다. 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문안에 무한정으로 내포될수 있다. 이와 같은 기능은 프로그램의 여러부분을 조건적으로 수행하기 위한 유연성을 제공한다.



else> <배열 연산자
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
제어 구조
wintermute
29-Aug-2007 12:45
Sinured: You can do the same thing with logical OR; if the first test is true, the second will never be executed.

<?PHP
if (empty($user_id) || in_array($user_id, $banned_list))
{
exit();
}
?>
Sinured
01-Aug-2007 11:59
As mentioned below, PHP stops evaluating expressions as soon as the result is clear. So a nice shortcut for if-statements is logical AND -- if the left expression is false, then the right expression can’t possibly change the result anymore, so it’s not executed.

<?php
/* defines MYAPP_DIR if not already defined */
if (!defined('MYAPP_DIR')) {
   
define('MYAPP_DIR', dirname(getcwd()));
}

/* the same */
!defined('MYAPP_DIR') && define('MYAPP_DIR', dirname(getcwd()));
?>
captainf
08-Mar-2007 07:53
@mongoose643

dougnoel was actually trying to provide a good example of how the if function automatically evaluates to false and goes no further if the first condition in an if expression fails can be used to optimize a script. In his example not everyone is an admin, and not all admins can delete. In his script it is an optimized failsafe to check if someone is an admin and has delete permissions while not wasting script time.
mongoose643 at gmail dot com
01-Mar-2007 06:03
@simplyduh

>Duh, both are booleans in the above case, and its obvious
>that checking one boolean is better than checking 2.

>if ($has_delete_permissions) would work better :)

I read dougnoel's post. He was providing an example of a BAD example. The last line in his post suggests that you NOT check for both - only the admin. So actually what he meant to check for is whether or not they are an admin. If so then they automatically have delete permissions - therefore it may be possible that no variable named "$has_delete_permissions" exists. The resulting statement would be as follows:

if($is_admin)
{
    //Statements to delete stuff go here.
}
dougnoel
05-May-2006 06:29
Further response to Niels:

It's not laziness, it's optimization.  It saves CPUs cycles.  However, it's good to know, as it allows you to optimize your code when writing.  For example, when determining if someone has permissions to delete an object, you can do something like the following:

if ($is_admin && $has_delete_permissions)

If only an admin can have those permissions, there's no need to check for the permissions if the user is not an admin.
niels dot laukens at tijd dot com
26-Dec-2004 07:49
For the people that know C: php is lazy when evaluating expressions. That is, as soon as it knows the outcome, it'll stop processing.

<?php
if ( FALSE && some_function() )
    echo
"something";
// some_function() will not be called, since php knows that it will never have to execute the if-block
?>

This comes in nice in situations like this:
<?php
if ( file_exists($filename) && filemtime($filename) > time() )
   
do_something();
// filemtime will never give an file-not-found-error, since php will stop parsing as soon as file_exists returns FALSE
?>

else> <배열 연산자
Last updated: Sun, 25 Nov 2007
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites