Wednesday, September 29, 2010

Changing Data Type with settype() in php

PHP provides the function settype() to change the type of a variable. To use
settype(), you must place the variable to change (and the type to change it to)
between the parentheses and separated by commas. Listing 4.5 converts 3.14 (a
double) to the four types that we are covering in this hour.

1: <html>
2: <head>
3: <title>Listing 4.5 Changing the type of a variable with settype()</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: print gettype( $undecided ); // double
9: print " -- $undecided<br>"; // 3.14
10: settype( $undecided, string );
11: print gettype( $undecided ); // string
12: print " -- $undecided<br>"; // 3.14
13: settype( $undecided, integer );
14: print gettype( $undecided ); // integer
15: print " -- $undecided<br>"; // 3
16: settype( $undecided, double );
17: print gettype( $undecided ); // double
18: print " -- $undecided<br>"; // 3.0
19: settype( $undecided, boolean );
20: print gettype( $undecided ); // boolean
21: print " -- $undecided<br>"; // 1
22: ?>
23: </body>
24: </html>
In each case, we use gettype() to confirm that the type change worked and then
print the value of the variable $undecided to the browser. When we convert the
string "3.14" to an integer, any information beyond the decimal point is lost forever.
That's why $undecided still contains 3 after we have changed it back to a double.
Finally, we convert $undecided to a boolean. Any number other than 0 becomes true
when converted to a boolean. When printing a boolean in PHP, true is represented
as 1 and false as an empty string, so $undecided is printed as 1.

No comments:

Post a Comment