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 `10 + 5 * 2`, the answer is `20` and not `30` because the multiplication `*` operator has a higher precedence than the addition  `+` operator.
Parentheses `()` may be used to force precedence, if necessary. For instance: `(10 + 5) * 2` evaluates to `30`.

## Associativity

Operators also have an associativity.
When operators have equal precedence their associativity decides how the operators are grouped.
For example:
`-` is left-associative, so `1 - 2 - 3` is grouped as `(1 - 2) - 3` and evaluates to `-4`.
`=` is right-associative, so `\$a = \$b = \$c` is grouped as `\$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 print
left and
left xor
left or
left `,`
Lowest Precedence

### Example:

``````<?php
\$n1 = 10;
\$n2 = 5;
\$n3 = 2;

\$ans = \$n1 + \$n2 * \$n3;
# * has higher precedence than +
# so first execute \$n2 * \$n3 the
echo "\$n1 + \$n2 * \$n3 = \$ans<br />";

\$ans = (\$n1 + \$n2) * \$n3;
# () has higher precedence than * so bracket execute first
# multiplied by \$n3 */
echo "(\$n1 + \$n2) * \$n3 = \$ans<br />";
?>``````

### Output:

Tutorialik.com
10 + 5 * 2 = 20
(10 + 5) * 2 = 30