Page 77 - Beginning PHP 5.3
P. 77
Chapter 3: PHP Language Basics
In the following example, a variable ’ s value is cast to various different types at the time that the
value is displayed:
$test_var = 8.23;
echo $test_var . “ < br / > ”; // Displays “8.23”
echo (string) $test_var . “ < br / > ”; // Displays “8.23”
echo (int) $test_var . “ < br / > ”; // Displays “8”
echo (float) $test_var . “ < br / > ”; // Displays “8.23”
echo (boolean) $test_var . “ < br / > ”; // Displays “1”
Note that $test_var ’ s type isn ’ t changed at any point; it remains a floating - point variable, containing
the value 8.23 , at all times. All that changes is the type of the data that ’ s passed to the echo statement.
Here ’ s the full list of casts that you can use in PHP:
Function Description
(int) value or (integer) value Returns value cast to an integer
(float) value Returns value cast to a float
(string) value Returns value cast to a string
(bool) value or (boolean) value Returns value cast to a Boolean
(array) value Returns value cast to an array
(object) value Returns value cast to an object
You can also cast a value to an integer, floating - point, or string value using three PHP functions:
Function Description
intval( value ) Returns value cast to an integer
floatval( value ) Returns value cast to a float
strval( value ) Returns value cast to a string
By the way, intval() has another use: converting from a non – base - 10 integer to a base - 10 integer. To
use this feature, pass intval() a string representation of the non – base - 10 integer, followed by the base
of the integer. For example, intval( “ 11 ” , 5 ) returns a value of 6 (the base - 5 number 11
converted to a decimal number).
39
9/21/09 8:51:23 AM
c03.indd 39 9/21/09 8:51:23 AM
c03.indd 39