Precedência de Operadores

A precedência de um operador especifica quem tem mais prioridade quando há duas delas juntas. Por exemplo, na expressão 1 + 5 * 3, a resposta é 16 e não 18 porque o operador de multiplicação ("*") tem prioridade de precedência que o operador de adição ("+"). Parênteses podem ser utilizados para forçar a precedência, se necessário. Assim, (1 + 5) * 3 é avaliado como 18.

Quando operadores tem precedência igual a associatividade decide como os operadores são agrupados. Por exemplo "-" é associado à esquerda, de forma que 1 - 2 - 3 é agrupado como (1 - 2) - 3 e resulta em -4. "=" por outro lado associa para a direita, de forma que $a = $b = $c é agrupado como $a = ($b = $c).

Operadores de igual precedência sem associatividade não podem ser utilizados uns próximos aos outros. Por exemplo 1 < 2 > 1 é ilegal no PHP. A expressão 1 <= 1 == 1 por outro lado é válida, porque o operador == tem menor precedência que o operador <=.

O uso de parenteses, embora não estritamente necessário, pode melhorar a leitura do código ao deixar o agrupamento explícito em vez de depender da associatividade e precedências implícitos.

A tabela seguinte mostra a precedência dos operadores, com a maior precedência no começo. Operadores com a mesma precedência estão na mesma linha, nesses casos a associatividade deles decidirá qual ordem eles serão avaliados.

Precedência dos operadores
Associação Operadores Informação Adicional
não associativo clone new clone e new
esquerda [ array()
direita ** aritmética
direita ++ -- ~ (int) (float) (string) (array) (object) (bool) @ types e incremento/decremento
não associativo instanceof tipos
direita ! lógicos
esquerda * / % aritmética
esquerda + - . aritmética e string
esquerda << >> bits
não associativo < <= > >= comparação
não associativo == != === !== <> <=> comparação
esquerda & bits e referências
esquerda ^ bits
esquerda | bits
esquerda && lógicos
esquerda || lógicos
direita ?? comparação
esquerda ? : ternário
direita = += -= *= **= /= .= %= &= |= ^= <<= >>= atribuição
esquerda and lógicos
esquerda xor lógicos
esquerda or lógicos

Exemplo #1 Associação

<?php
$a 
5// (3 * 3) % 5 = 4
// associação do operador ternário difere do C/C++
$a true true 2// (true ? 0 : true) ? 1 : 2 = 2

$a 1;
$b 2;
$a $b += 3// $a = ($b += 3) -> $a = 5, $b = 5
?>

A precedência e associatividade apenas determinam como as expressões são agrupadas, mas não especificam a ordem de avaliação. O PHP (geralmente) não especifica em que ordem as expressões são avaliadas, então códigos que assumem ordens específicas de avaliação devem ser evitados porque o comportamento pode ser alterado entre versões do PHP ou dependendo do código em volta.

Exemplo #2 Ordem de avaliação não definida

<?php
$a 
1;
echo 
$a $a++; // pode imprimir 2 ou 3

$i 1;
$array[$i] = $i++; // pode definir o índice 1 ou 2
?>

Exemplo #3 +, - and . possuem a mesma precedência

<?php
$x 
4;
// esta linha pode resultar em uma saída inesperada:
echo "x menos um é igual a " $x-", ou assim eu espero\n";
// porque é avaliada como esta linha:
echo (("x menos um é igual a " $x) - 1) . ", ou assim eu espero\n";
// a precedência desejada pode ser aplicada utilizando parênteses:
echo "x menos um é igual a " . ($x-1) . ", ou assim eu espero\n";
?>

O exemplo acima irá imprimir:

-1, ou assim eu espero
-1, ou assim eu espero
x menos um é igual a 3, ou assim eu espero

Nota:

Embora o = tenha uma precedência menor que a maioria dos operadores, o PHP ainda permite expressões similares a if (!$a = foo()), onde o valor retornado de foo() é colocado em $a.

add a note add a note

User Contributed Notes 8 notes

up
167
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
46
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
7
ivan at dilber dot info
7 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
4
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
-1
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
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
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.
To Top