Type Conversion

PHP provides several mechanisms to allow variables of one type to be considered as another type. Variables can be explicitly converted to another type with the following functions:

string strval(mixed variable)
integer intval(mixed variable)
float floatval(mixed variable)

The function settype(mixed variable, string type) can explicitly set the type of variable to type, where type is again one of array, boolean, float, integer, object, or string.

PHP supports type-casting in much the same way as C, to allow the type of an expression to be changed. By placing the type name in parentheses in front of a variable, PHP converts the value to the desired type:

(int) $var

or (integer) $var

Cast to integer
(bool) $var

or (boolean) $var

Cast to Boolean
(float) $var, (double) $var

or (real) $var

Cast to float
(string) $var Cast to string
(array) $var Cast to array
(object) $var Cast to object

The rules for converting types are mostly common sense, but some conversions may not appear so straightforward. Table 2-1 shows how various values of $var are converted using the (int), (bool), (string), and (float) casting operators.

Table 2-1. Examples of type conversion in PHP using casting operators
Value of $var (int) $var (bool) $var (string) $var (float) $var
null 0 false "" 0
true 1 true "1" 1
false 0 false "" 0
0 0 false "0" 0
3.8 3 true "3.8" 3.8
"0" 0 false "0" 0
"10" 10 true "10" 10
"6 feet" 6 true "6 feet" 6
"foo" 0 true "foo" 0