Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

Listing 2.12 String/Number Conversion


<?
//1 + 1 == 2
print((1 + "1"). "
\n");


//1 + 2 == 3
print((1 + " 2"). "
\n");


//1 + 3 == 4
print((1 + "3extra stuff"). "
\n");


//1 + 4500000 == 4500001
print((1 + "4.5e6"). "
\n");


//1 + 0 == 1
print((1 + "a7"). "
\n");
?>


Listing 2.12 is a good test of how PHP will convert strings to numbers. All the
commands will produce a number from the string, except the last. Since the string in the
last line begins with a letter, PHP gives up and treats it as zero. Notice that after the
addition the script uses a concatenation operator. This causes the integer created inside
the parentheses to be converted to a string for the purposes of printing. The concatenation
operator forces both sides to be treated as strings.


Listing 2.13 demonstrates the use of parentheses to force the order in which the
expression is evaluated. The first line evaluates to 17, the second to 35. In addition to
evaluation from left to right, operators execute in a specific precedence. For example,
multiplication is resolved before addition.


A programming language must order all its operators, but in practice it is difficult for the
programmer to keep it all straight. The best policy is to use parentheses to explicitly force
the precedence you want on complex expressions. Table 2.11 lists the operators in order
of precedence. Operators on the same line are of equal precedence, therefore falling back
to left-to-right precedence.


Listing 2.13 Using Parentheses


<?
print ((3 + 2 7). "
\n");
print (((3 + 2)
7). "
\n");
?>
Table 2.11. Precedence of Operators
Highest []^


() {}^
~! ++ -- - $ & @^
(double) (integer) (string) (array) (object)



  • / %^



  • -.^

Free download pdf