Automatic type conversion

Automatic type conversion occurs when two differently typed variables are combined in an expression or when a variable is passed as an argument to a library function that expects a different type. When a variable of one type is used as if it were another type, PHP automatically converts the variable to a value of the required type. The same rules are used for automatic type conversion as are demonstrated in Table 2-1.

Some simple examples show what happens when strings are added to integers and floats and when strings and integers are concatenated:

// $var is set as an integer = 115
$var = "100" + 15;
// $var is set as a float = 115.0
$var = "100" + 15.0;
// $var is set as a string = "39 Steps"
$var = 39 . " Steps";

Not all type conversions are so obvious and can be the cause of hard-to-find bugs:

// $var is set as an integer = 39
$var = 39 + " Steps";
// $var is an integer = 42
$var = 40 + "2 blind mice";
// $var is a float, but what does it mean
$var = "test" * 4 + 3.14159;

Automatic type conversion can change the type of a variable. Consider the following example:

$var = "1"; // $var is a string == "1"
$var += 2;  // $var is now an integer == 3
$var /= 2;  // $var is now a float == 1.5
$var *= 2;  // $var is still a float == 3

Care must be taken when interpreting non-Boolean values as Boolean. Many library functions in PHP return values of different types: false if a valid result could not be determined, or a valid result. A valid return value of 0, 0.0, "0", an empty string, null, or an empty array is interpreted false when used as a Boolean value.

The solution is to test the type of the variable using the functions described in the next section.