05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Number of Operands<br />

Most operators in <strong>PHP</strong> are binary operators; they combine two operands (or expressions)<br />

into a single, more complex expression. <strong>PHP</strong> also supports a number of unary<br />

operators, which convert a single expression into a more complex expression.<br />

Finally, <strong>PHP</strong> supports a single ternary operator that combines three expressions into<br />

a single expression.<br />

Operator Precedence<br />

The order in which operators in an expression are evaluated depends on their relative<br />

precedence. For example, you might write:<br />

2 + 4 * 3<br />

As you can see in Table 2-3, the addition and multiplication operators have different<br />

precedence, with multiplication higher than addition. So the multiplication happens<br />

before the addition, giving 2+12,or14, as the answer. If the precedence of addition<br />

and multiplication were reversed, 6*3, or 18, would be the answer.<br />

To force a particular order, you can group operands with the appropriate operator in<br />

parentheses. In our previous example, to get the value 18, you can use this expression:<br />

(2 + 4) * 3<br />

It is possible to write all complex expressions (expressions containing more than a<br />

single operator) simply by putting the operands and operators in the appropriate<br />

order so that their relative precedence yields the answer you want. Most programmers,<br />

however, write the operators in the order that they feel makes the most sense<br />

to programmers, and add parentheses to ensure it makes sense to <strong>PHP</strong> as well. Getting<br />

precedence wrong leads to code like:<br />

$x + 2 / $y >= 4 ? $z : $x

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!