﻿ ﻿
﻿

Precedence of Operations

This section provides the order of precedence for operations commonly used in PHP. Operations in a complex expression must be evaluated according to the order of operation precedence.

﻿

In the previous section, we learned that operations in a complex expression must be evaluated according to the order of operation precedence. The following table shows you the relative order of precedence for some commonly used operations:

```Precedence   Operations       Notes
16           (...)            Operation group
15           ++ --            Increment/decrement
14           ~ -              Unary negation
13           !                Logical not
12           * / %            Multiplication, Division, ...
11           + -              Addition and Subtraction
10           .                String concatenation
9            << >>            Bitwise shift
8            < > <= >=        Comparisons
7            == != <> === !== Comparisons
6            &                Bitwise and
5            ^                Bitwise xor
4            |                Bitwise or
3            && And           Logical and
2            xor              Logical xor
1            || Or            Logical or
0            = += -= ...      Assignments
```

Remember that:

• Operations with higher precedence values must be evaluated first.
• Operations of the same precedence value must be evaluated from left to right.

To show you some of reference rules mentioned above, I wrote the following PHP script, PrecedenceTest.php:

```<?php
#  PrecedenceTest.php
#
print "\n Arithmetic, comparison and logical Operations:\n";
print "    : ". (1 + 2 * 3 / 4) ."\n";
print "    : ". (1 + 2 * 3 / 4 < 5 != FALSE) ."\n";
print "    : ". (1 + 2 * 3 / 4 < 5 != FALSE || 6 < 7) ."\n";

print "\n Operations with groups:\n";
print "    : ". (((1 + (2 * 3 / 4) < 5) != FALSE) || 6 < 7) ."\n";
print "    : ". ((1 + (2 * 3 / 4) < 5) != (FALSE || 6 < 7)) ."\n";

print "\n Bitwise Operations:\n";
print "    : " . (0x0001 | 0x00FF & 0x3210 << 4) . "\n";
print "    : " . ((0x0001 | 0x00FF) & 0x3210 << 4) . "\n";
print "    : " . (0x0001 | (0x00FF & 0x3210) << 4) . "\n";
print "    : " . (0x0001 | 0x00FF & (0x3210 << 4)) . "\n";
?>
```

If you run this sample script, you should get:

```C:\herong> \php\php PrecedenceTest.php

Arithmetic, comparison and logical Operations:
: 2.5
: 1
: 1

Operations with groups:
: 1
:

Bitwise Operations:
: 1
: 0
: 257
: 1
```

Last update: 2019.

﻿

﻿ ﻿