Operator Precedence in PHP
PHP Operators – Part 7
Forward: In this part of the series we look at operator precedence in PHP.
By: Chrysanthus Date Published: 10 Aug 2012
Introduction
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
Example
Consider the following statement:
$x = 2 + 5 * 3;
There are three operators here, which are =, + and *. Now = is of a very low precedence and it is executed last. The question then is between + and -; which is executed first? If the multiplication operator, * is executed first, the answer will be 17. If the addition operator is executed first, the answer will be 21. Well, in PHP, * is of a higher precedence than +, so * is executed first and the answer is 21. You can force the + to be executed first by using brackets, as follows:
int x = (2 + 8) * 5;
Whenever you are in doubts of which operator would be executed first, use brackets, to be sure that an operator would be executed first. Brackets can be nested.
Associativity means operation from left to right or operation from right to left. Left associativity means that the operation of the operator is from left to right. Right associativity means the operation is from right to left. This has been indicated in the previous parts of the series, but the word, associativity was not mentioned. In the absence of brackets, if a series of operators (with their operands) are of the same level, then associativity is used in the series of operations.
Still on associativity, consider the following expression:
9-4-2
Subtraction is left associative, so the 9-4 is done first to give 5-2 = 3 instead of 4-2 first, to result in 9-2 = 7.
Precedence Order
Increment/Decrement Operators
++ --
Associativity: Non-associative
Not Operator
!
Associativity: Right-to-Left
Array Operator
[
Associativity: Left-to-Right
Multiplicative Operators
% * /
Associativity: Left-to-right
Additive and String Operators
+ - .
Associativity: Left-to-right
Comparison Operators
< <= > >= <>
Associativity: Non-associative
Equality and Identity Operators
== != === !==
Associativity: Non-associative
Reference Operator
&
Associativity: Left-to-right
Logical AND Operator
&&
Associativity: Left-to-right
Ternary Operator
? :
Associativity: Left-to-right
Assignment Operators
= += -= *= /= .= %=
Associativity: Right-to-Left
Logical WORD AND Operator
and
Associativity: Left-to-right
Logical Exclusive Or Operator
xor
Associativity: Left-to-right
Logical or Operator
or
Associativity: Left-to-right
Comma Operator
,
Associativity: Left-to-right
Well, we have seen a lot in this series. We should really take a break here. We continue in the next part.
Chrys
Related Links
The New HTML CanvasMajor in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course