Page 45 - Open Soource Technologies 304.indd
P. 45
Unit 2: Language Basics
Notes
10 L ^ Bitwise XOR
9 L | Bitwise OR
8 L && Logical AND
7 L || Logical OR
6 L ?: Conditional operator
5 L = Assignment
L +=, -=, *=, /=, .=, %=, &=, |=, ^=, ~=, <<=, >>= Assignment with operation
4 L and Logical AND
3 L xor Logical XOR
2 L or Logical OR
1 L , List separator
2.4.1 Number of Operands
Most operators in PHP are binary operators; they combine two operands (or expressions) into a
single, more complex expression. PHP also supports a number of unary operators, which convert a
single expression into a more complex expression. Finally, PHP supports a single ternary operator
that combines three expressions into a single expression.
2.4.2 Operator Precedence
The order in which operators in an expression are evaluated depends on their relative precedence.
For example, you might write:
2 + 4 * 3
As you can see in Table 2.1, the addition and multiplication operators have different precedence,
with multiplication higher than addition. So the multiplication happens before the addition,
giving 2 + 12, or 14, as the answer. If the precedence of addition and multiplication were
reversed, 6 * 3, or 18, would be the answer.
To force a particular order, you can group operands with the appropriate operator in parentheses.
In our previous example, to get the value 18, you can use this expression:
(2 + 4) * 3
It is possible to write all complex expressions (expressions containing more than a single operator)
simply by putting the operands and operators in the appropriate order so that their relative
precedence yields the answer you want. Most programmers, however, write the operators in
the order that they feel makes the most sense to programmers, and add parentheses to ensure it
makes sense to PHP as well. Getting precedence wrong leads to code like:
$x + 2 / $y >= 4 ? $z : $x << $z
This code is hard to read and is almost definitely not doing what the programmer expected it to do.
One way many programmers deal with the complex precedence rules in programming languages
is to reduce precedence down to two rules:
• Multiplication and division have higher precedence than addition and subtraction.
• Use parentheses for anything else.
Operator precedence should be used based on precedence, otherwise result
will affect.
LOVELY PROFESSIONAL UNIVERSITY 39