논리 연산자

논리 연산자

PHP에는 여러 논리 연산자가 있어요. and, or, xor 같은 단어형 연산자와 &&, || 같은 기호형 연산자인데, 둘은 우선순위가 달라요.

출처: Logical Operators

본문

논리 연산자를 표로 정리하면 이렇게 돼요.

예시 이름 결과
$a and $b And $a와 $b가 모두 true일 때 true
$a or $b Or $a 또는 $b 중 하나가 true일 때 true
$a xor $b Xor $a 또는 $b 중 하나만 true일 때 true (둘 다는 안 됨)
! $a Not $a가 true가 아닐 때 true
$a && $b And $a와 $b가 모두 true일 때 true
$a || $b Or $a 또는 $b 중 하나가 true일 때 true

"and""or" 연산자에 두 가지 변형이 있는 이유는, 두 연산자가 서로 다른 우선순위에서 동작하기 때문이에요. (연산자 우선순위(Operator Precedence)를 참고하세요.)

Example #1 논리 연산자 예시

<?php

// --------------------
// foo() will never get called as those operators are short-circuit

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

// --------------------
// "||" has a greater precedence than "or"

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f before the "or" operation occurs
// Acts like: (($f = false) or true)
$f = false or true;

var_dump($e, $f);

// --------------------
// "&&" has a greater precedence than "and"

// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;

// The constant true is assigned to $h before the "and" operation occurs
// Acts like: (($h = true) and false)
$h = true and false;

var_dump($g, $h);
?>

위 예제의 출력은 대략 다음과 같아요.

bool(true)
bool(false)
bool(false)
bool(true)

더 알아보기

  • 연산자 우선순위(Operator Precedence)