Operators


PHP comes with a number of operators for working on your data, and they appear in Table A-1.

For example, here are the PHP math operators:

+

Adds two numbers

-

Subtracts one number from another

*

Multiplies two numbers together

/

Divides one number by another

%

Returns the remainder when one number is divided by another (modulus)


You can see them all at work in this example:

 <HTML>     <BODY>         <H1>Using the PHP math operators</H1>         <?php             echo "9 + 4 = ", 9 + 4;             echo "9 - 4 = ", 9 - 4;             echo "9 * 4 = ", 9 * 4;             echo "9 / 4 = ", 9 / 4;             echo "9 % 4 = ", 9 % 4;         ?>     </BODY> </HTML> 

Operator precedence is also an issueif you evaluate this statement, what would be the result?

 <?php     echo 4 + 2 * 9; ?> 

Will this be 4 + 2 * 9 = 6 * 9 = 54, or will the * be evaluated first, giving 4 + 2 * 9 = 4 + 18 = 22? In this case, you get 22 because the * operator has precedence over the + operator when you mix them up. Operator precedence, from highest to lowest, is shown in Table A-2.

Table A-2. Operators in Descending Order of Precedence

Operators

new

[

! ~ ++ -- (int) (float) (string) (array) (object)

@

* / %

+ -.

<< >>

< <= > >=

== != === !==

&

^

|

&&

||

? :

= += -= *= /= .= %= &= |= ^= <<= >>=

print

and

xor

or

,


You can always use parentheses to tell PHP what to do if you're unsure about precedence. If you change this expression to (4 + 2) * 9, then you'll get 6 * 9 = 54:

 <?php     echo "4 + 2 * 9 = ", 4 + 2 * 9;     echo "(4 + 2) * 9", (4 + 2) * 9;     echo "4 + (2 * 9)", 4 + (2 * 9); ?> 

Here, you'd get 22, 54, and 22.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net