HomeCoding & Programming

PHP Operator Precedence and Associativity

PHP Operator Precedence and Associativity
Like Tweet Pin it Share Share Email

PHP as usual all languages has a set of rules (known as Operator Precedence) that decide how complicated expressions are processed.

 

$myVar = 2 * 10 – 1;

Should $myVar be 19 or 18?

 

If you cannot decide why there are two possibilities, break them up using parentheses like this

 

$myVar = (2 * 10) – 1
$myVar = 2 * (10 – 1);

 

In the first example, 2 is multiplied by 10, then 1 is subtracted from the result, but in the second one, 1 has subtracted from 10 and multiplied by 2 makes it 18.If there is ambiguity in your expressions, PHP will resolve them according to its internal set of rules called as Operator Precedence.

 

The precedence of an operator is important to bind two expressions together. In the expression 2 + 5 * 3, the answer is 17 and not 21 because the “*” operator has a higher precedence than the “+” operator.

 

If operator precedence is equal, left to right associativity is used.

The following table lists the precedence of operators with the highest-precedence operators listed at the top.

 

Associativity Operators Additional Information
non-associative clone new clone and new
left [ array()
non-associative ++ — increment/decrement
non-associative ~ – (int) (float) (string) (array) (object) (bool) @ types
non-associative instanceof types
right ! Logical
left * / % arithmetic
left + – . arithmetic and string
left << >> bitwise
non-associative < <= > >= <> comparison
non-associative == != === !== comparison
left & bitwise and references
left bitwise
left | bitwise
left && logical
left || logical
left ? : ternary
right = += -= *= /= .= %= &= |= = <<= >>= assignment
left and logical
left xor logical
left or logical
left , many uses

Comments (2)

  • Hello would you mind letting me know which web host you’re working with? I’ve loaded your blog in 3
    different browsers and I must say this blog loads a lot quicker then most.

    Can you suggest a good hosting provider at a fair price?
    Kudos, I appreciate it!

    • Author

      HostBig .. I am using you can find the link of the same in the banner below.

Comments are closed.