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();
}
?>
제어 구조
Table of Contents
- else
- elseif
- 제어 구조의 대체 문법
- while
- do-while
- for
- foreach
- break
- continue
- switch
- declare
- return
- require
- include
- require_once
- include_once
모든 PHP 스크립트는 연속적인 구문으로 이루어진다. 하나의 구문은 지정문 이 될수도 있고, 함수 호출, 반복문, 조건문이 될수 있으며 심지어는 아무 내용이 없는 빈 문장일수도 있다. 한 구문은 보통 세미콜론(;)으로 끝난다. 또한 여러개의 구문을 중괄호({,})를 사용하여 하나의 그룹으로 만들어 사용할 수도 있다. 이 구문 그룹은 그 그룹의 모든 구문들이 하나의 구문인 것처럼 인식된다. 이 장에서는 여러 가지 구문형태에 대해 알아본다.
if
if문은 PHP를 포함해서 모든 언어에 있어서 가장 중요한 기능(feature) 중 하나이다. 이 제어문으로 각각 다른 코드에 대해 조건적인 수행을 가능케한다. if문의 기능은 C와 비슷하다:
if (expr)
statement
표현식에 관한 섹션에서 설명된것처럼 expr은 논리(Boolean)값으로 취급된다. expr이 TRUE와 같다면 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문안에 무한정으로 내포될수 있다. 이와 같은 기능은 프로그램의 여러부분을 조건적으로 수행하기 위한 유연성을 제공한다.
제어 구조
30-Aug-2007 04:45
02-Aug-2007 03: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()));
?>
06-May-2006 10: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.
27-Dec-2004 12: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
?>
