05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The division and multiplication operators have the same precedence, but the result<br />

of the expression depends on which operation we do first:<br />

2/(2*2) // 0.5<br />

(2/2)*2 // 2<br />

The division and multiplication operators are left-associative; this means that in<br />

cases of ambiguity, the operators are evaluated from left to right. In this example, the<br />

correct result is 2.<br />

Implicit Casting<br />

Many operators have expectations of their operands—for instance, binary math<br />

operators typically require both operands to be of the same type. <strong>PHP</strong>’s variables can<br />

store integers, floating-point numbers, strings, and more, and to keep as much of the<br />

type details away from the programmer as possible, <strong>PHP</strong> converts values from one<br />

type to another as necessary.<br />

The conversion of a value from one type to another is called casting. This kind of<br />

implicit casting is called type juggling in <strong>PHP</strong>. The rules for the type juggling done by<br />

arithmetic operators are shown in Table 2-4.<br />

Table 2-4. Implicit casting rules for binary arithmetic operations<br />

Type of first operand Type of second operand Conversion performed<br />

Integer Floating point The integer is converted to a floating-point number<br />

Integer String The string is converted to a number; if the value after conversion is a<br />

floating-point number, the integer is converted to a floating-point<br />

number<br />

Floating point String The string is converted to a floating-point number<br />

Some other operators have different expectations of their operands, and thus have<br />

different rules. For example, the string concatenation operator converts both operands<br />

to strings before concatenating them:<br />

3 . 2.74 // gives the string 32.74<br />

You can use a string anywhere <strong>PHP</strong> expects a number. The string is presumed to<br />

start with an integer or floating-point number. If no number is found at the start of<br />

the string, the numeric value of that string is 0. If the string contains a period (.) or<br />

upper- or lowercase e, evaluating it numerically produces a floating-point number.<br />

For example:<br />

"9 Lives" – 1; // 8 (int)<br />

"3.14 Pies" * 2; // 6.28 (float)<br />

"9 Lives." – 1; // 8 (float)<br />

"1E3 Points of Light" + 1; // 1001 (float)<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Expressions and Operators | 37

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

Saved successfully!

Ooh no, something went wrong!