# Operators precedence and associativity in PHP

by anonymous

• 0
• 0
• 0
78 views
```Orignal Source:http://codingvilla.com/operators-precedence-associativity-php-single-article-599.aspx
Operator Precedence and associativity in php

Operators have a set precedence, mean order, in which they are solved or calculated.

Operators also have associativity, which is the order in which operators of the same precedence are calculated. This order is generally left to right (called left) right to left (called right).

Operators and their associativity

[ ,*, /, %, +, -, ., << >> ,&, | ,&&, ||, ? :, xor all have left associativity.

= += -= *= /= .= %= &= |= = <<= >>= all have right associativity.

++ -- increment and decrement are non-associative

Examples

Code:

<?php
/* Precedence Example */
\$var1 = 4 + 2 * 8;
echo "\\$var1=\$var1";
echo "<br/>";
/* Associativity Example */
\$var2 = 3 / 3 * 4;
echo "\\$var2=\$var2";
?>

Output:

\$var1=20\$var2=4

Explanation:

In the above example we have two codes first describe precedence and other one describes associativity. Precedence means order in which operators are evaluated. Multiply operator has higher precedence then + operator so it is evaluated first then its result is added with other operand.

Associativity means operators having same precedence are calculated in the above example operators *,/ have same precedence so calculated by associativity.

Code:

<?php

\$var1 = 1 && 0 || 1;
echo "\\$var1=\$var1";
echo "<br/>";

\$var2 = 1 || 0 && 1;
echo "\\$var2=\$var2";
echo "<br/>";

?>

Output:

\$var1=1\$var2=1

Explanation:

In the above example we have two codes first describe precedence and other one describes associativity. Precedence means order in which operators are evaluated. AND operator (&&), and OR operator have same precedence so they are evaluated by their associativity.

Code:

<?php
\$var1 = 1 << 0 && 1;
echo "\\$var1=\$var1";
echo "<br/>";

\$var2 = 1 << 0 && 1;
echo "\\$var2=\$var2";
echo "<br/>";
?>

Output:

\$var1=1\$var2=1

Explanation:

Firstly the operator (<<) have higher precedence so it is evaluated first then its result is evaluated with && and third operand.```