PHP
Operator Precedence

The precedence of an operator specifies how "tightly" it binds two expressions together.

In general, operators have a set precedence, or order, in which they are evaluated.

For example, in the expression

, the answer is *10 + 5 * 2*`2`

and not *0*`30`

because the multiplication `*`

operator has a higher precedence than the addition `+`

operator.

Parentheses `()`

may be used to force precedence, if necessary. For instance:

evaluates to *(10 + 5) * 2*

.*30*

Operators also have an associativity.

When operators have equal precedence their associativity decides how the operators are grouped.

For example:

`-`

is left-associative, so

is grouped as *1 - 2 - 3*

and evaluates to *(1 - 2) - 3*

.*-4*

`=`

is right-associative, so

is grouped as *$a = $b = $c*`$a = ($b = $c)`

.

Following Table shows operator **precedence** and **associativity** in PHP, where operators with the lowest precedence are at the top, and precedence increases as you go down the table.

Associativity | Operators |
---|---|

Highest Precedence | |

n/a | `()` |

n/a | new |

right | `[]` |

right | `!` `~` `++` `--` `(int)` `(double)` `(string)` `(array)` `(object)` |

left | `*` `/` `%` |

left | `+` `-` `.` |

left | `<<` `>>` |

n/a | `<` `<=` `>` `>=` |

n/a | `==` `!=` `===` `!===` |

left | & |

left | ^ |

left | | |

left | && |

left | || |

left | ? : |

left | `=` `+=` `-=` `*=` `/=` `.=` `%=` `|=` `^=` `~=` `<<=` `>>=` |

right | |

left | and |

left | xor |

left | or |

left | `,` |

Lowest Precedence |

```
<?php
$n1 = 10;
$n2 = 5;
$n3 = 2;
$ans = $n1 + $n2 * $n3;
# * has higher precedence than +
# so first execute $n2 * $n3 the
# answer is added to $n1 which is
echo "$n1 + $n2 * $n3 = $ans<br />";
$ans = ($n1 + $n2) * $n3;
# () has higher precedence than * so bracket execute first
# which is ($n1 + $n2) after addition answer is
# multiplied by $n3 */
echo "($n1 + $n2) * $n3 = $ans<br />";
?>
```

10 + 5 * 2 = 20

(10 + 5) * 2 = 30

(10 + 5) * 2 = 30

## Share This Page to Download:

Download