연산자 우선권

연산자 우선권은 두 표현이 얼마나 "단단하게" 묶여 있는지 정의합니다. 예를 들어, 1 + 5 * 3 표현의 답은 18이 아닌 16입니다. 곱셈("*") 연산자가 덧셈(+) 연산자보다 높은 우선권을 가지기 때문입니다. 필요하다면, 우선권을 강제하기 위해 괄호를 사용할 수 있습니다. 예를 들면: (1 + 5) * 318로 평가됩니다. 연산자 우선권이 같으면, 왼쪽에서 오른쪽 결합을 사용합니다.

다음 표는 높은 우선권을 가지는 연산자가 위쪽에 나오는 연산자 우선권 목록입니다. 같은 줄에 있는 연산자는 같은 우선권을 가지며, 이 경우 결합이 평가하는 순서를 결정합니다.

연산자 우선권
결합 연산자 추가 정보
무결합 clone new clonenew
왼쪽 [ array()
무결합 ++ -- 증가/감소
무결합 ~ - (int) (float) (string) (array) (object) (bool) @ 자료형
무결합 instanceof 자료형
오른쪽 ! 논리
왼쪽 * / % 계산
왼쪽 + - . 계산 그리고 문자열
왼쪽 << >> 비트
무결합 < <= > >= <> 비교
무결합 == != === !== 비교
왼쪽 & 비트 그리고 참조
왼쪽 ^ 비트
왼쪽 | 비트
왼쪽 && 논리
왼쪽 || 논리
왼쪽 ? : 삼항
오른쪽 = += -= *= /= .= %= &= |= ^= <<= >>= 할당
왼쪽 and 논리
왼쪽 xor 논리
왼쪽 or 논리
왼쪽 , 다양한 사용

왼쪽 결합은 표현이 왼쪽에서 오른쪽으로 평가됨을 의미하며, 오른쪽 결합은 반대입니다.

Example #1 결합성

<?php
$a 
5// (3 * 3) % 5 = 4
$a true true 2// (true ? 0 : true) ? 1 : 2 = 2

$a 1;
$b 2;
$a $b += 3// $a = ($b += 3) -> $a = 5, $b = 5
?>
괄호를 사용하는 것은 표현의 가독성을 증가시킵니다.

Note:

=이 대부분의 연산자보다 낮은 우선권을 가지지만, PHP는 다음과 같은 표현을 허용합니다: if (!$a = foo()), 이 경우 foo()의 반환값은 $a에 들어갑니다.

add a note add a note

User Contributed Notes 8 notes

up
170
fabmlk
8 years ago
Watch out for the difference of priority between 'and vs &&' or '|| vs or':
<?php
$bool
= true && false;
var_dump($bool); // false, that's expected

$bool = true and false;
var_dump($bool); // true, ouch!
?>
Because 'and/or' have lower priority than '=' but '||/&&' have higher.
up
27
aaronw at catalyst dot net dot nz
6 years ago
If you've come here looking for a full list of PHP operators, take note that the table here is *not* complete. There are some additional operators (or operator-ish punctuation tokens) that are not included here, such as "->", "::", and "...".

For a really comprehensive list, take a look at the "List of Parser Tokens" page: http://php.net/manual/en/tokens.php
up
48
Carsten Milkau
11 years ago
Beware the unusual order of bit-wise operators and comparison operators, this has often lead to bugs in my experience. For instance:

<?php if ( $flags & MASK  == 1) do_something(); ?>

will not do what you might expect from other languages. Use

<?php if (($flags & MASK) == 1) do_something(); ?>

in PHP instead.
up
11
ivan at dilber dot info
6 years ago
<?php
// Another tricky thing here is using && or || with ternary ?:
$x && $y ? $a : $b// ($x && $y) ? $a : $b;

// while:
$x and $y ? $a : $b// $x and ($y ? $a : $b);

?>
up
1
instatiendaweb at gmail dot com
3 years ago
//incorrect
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2
//Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)`
//correct
$a = (true ? 0 : true) ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

==> correction documentation.
up
0
noone
4 years ago
Something that threw me of guard and I hadn't found it mentioned anywhere is if you're looking to asign a value in an if statement condition and use the same value in the said condition and compare it to a different value note the precedence of operators.

if($a=5&&$a==5){
  echo '5';
} else {
  echo 'not 5';
}
//echos  not 5

You'll get a Notice:  Undefined variable: a;
This happens because the expression is treated as
($a=5&&($a==5))
In this case $a was undefined.

Use parentheses to enforce the desired outcome or and instead of &&.
if(($a=5)&&$a==5){ // or $a=5 and $a==5
  echo '5';
} else {
  echo 'not 5';
}

//echos  5

We get no notice!

A use case for this can be a three part condition that first checks if a value is valid, second assigns a new variable based on the first value and then checks if the result is valid.

$ID=100;

if ($ID&&($data=get_table_row_for_ID($ID))&&$data->is_valid()) { //NOTE: assigned $data
// do something with the data
}

If assigning variables in an if condition I recommend adding a comment at the end of the line that such an action took place.
up
1
karlisd at gmail dot com
8 years ago
Sometimes it's easier to understand things in your own examples.
If you want to play around operator precedence and look which tests will be made, you can play around with this:

<?php
function F($v) {echo $v." "; return false;}
function
T($v) {echo $v." "; return true;}

IF (
F(0) || T(1) && F(2)  || F(3)  && ! F(4) ) {
  echo
"true";
} else echo
" false";
?>
Now put in IF arguments f for false and t for true, put in them some ID's. Play out by changing "F" to "T" and vice versa, by keeping your ID the same. See output and you will know which arguments  actualy were checked.
up
-2
anisgazig at gmail dot com
3 years ago
Three types of operator associativity in php.
1.left
2.rigt
3.non-associativity

Category of three operators are right associativity
1)**
2)=,+=,-=,*=,/=,%=,&=,^=,|=,<<=,>>=,??=,.=
3)??

Category of eight operators are non-associativity
1)clone new
2)++,--,~,@
3)!
4)<,<=,>,>=
5)<<,>>
6)yield from
7)yield
8)print

Rest of the operators are left associativity
To Top