As we alluded to before, PHP is a richly typed languageall variables and objects in the language have a known type. However, PHP is a bit different from other languages with which programmers might be familiar, since variables are not declared as being of a certain type, and the language engine freely converts between the different types at run-time.
In this section, we discuss the rules and behaviors for converting between the various types in PHP and some of the more unexpected results you might see.
There are two primary ways to convert variables of one type to another.
Implicit Type Conversions
The most common way you will see variables of one type converted to another is via an implicit conversion, or a conversion that the PHP language engine does automatically. Instead of requiring variables to be declared as a certain type, PHP automatically determines the type of the variable for us. When it executes an operation that either expects a specific type or requires two variables to be of the same type, it does its best to convert the data for us.
The most common places you will see implicit (automatic) type conversions are:
Explicit Type Conversions
For those cases where PHP might not normally convert variables, either to a particular type you desire or not at all, you have the option of explicitly forcing the language to attempt a type conversion by using what is called type casting. In this, you prefix a variable (or any expression) with a type surrounded by parentheses, and PHP attempts the conversion for you. You may use the following casts:
For example, if the user fills in a form to purchase some books from our site and his browser sends us the details, the quantity desired might come in as the string "3". We want this in integer format, so we might choose to use a cast integer to do this.
<?php // don't worry about the $_POST array you'll see // it again soon! $quantity_string = $_POST['quantity_desired']; $quantity_desired = (int)$quantity_string; ?>
Specific Type Conversions
The exact way in which variables or expressions of one type are converted to another is not always obvious, so we will now discuss the key type conversions that PHP will perform. You are encouraged to be a bit cautious when doing conversions and to verify the results carefully to make sure that what you expect to happen actually does. Much time can be spent trying to figure out why a script does not work when you make assumptions here and there that are not quite correct.
Conversion to Integers
When converting floating-point values to integers, PHP rounds the values to zero. Floating-point values greater than the maximum or lesser than the minimum integer value on the system give an undefined result when cast to an integer. (No errors will be generated.) If you were to run the following script
<?php echo (int)4.999; echo "<br/>"; echo (int)-6.54321; // it will round toward zero echo "<br/>"; echo (int)1000000000000; // too big for an int !!! echo "<br/>"; ?>
you would see the following output. (The last one varies depending on your computer setup.)
4 -6 -727379968
When converting from a string to an integer, PHP analyzes the string one character at a time until it finds a non-digit character. (The number may, optionally, start with a + or - sign.) The resulting number is parsed as a decimal number (base-10). A failure to parse a valid decimal number returns the value 0.
<?php echo (int)"123"; // prints 123 echo (int)"+5555"; // 5555 echo (int)"55e2"; // 55 - parsing stops at the e echo (int)"3 little pigs"; // 3 - parsing stops at space echo (int)"Three little Pigs"; // 0 - no natural languages... echo (int)"0123"; // 123 decimal only echo (int)"0xff"; // 0 - decimal only, stops at x echo (int)"-4321"; // -4321 negative numbers ok echo (int)"-23434 happy cows"; // -23434 stops at space echo (int)".324243"; // 0 stops at . echo (int)"beeepbeeep!"; // 0 stops at b ?>
Note in the previous example above that the string "0123" does not get interpreted as the octal value 123 (decimal 83), but instead is treated as a decimal number with an extra zero in front of it.
When converting from a Boolean to an integer, FALSE will return 0 while trUE will return 1.
Converting from arrays, objects, or resources to integers is undefined and should not be attempted or relied upon to produce predictable results.
Conversions to Floating-Point Numbers
Integers are easily converted to floating-point numbers but, as we have warned in the past, the float value might not be the same as the original integer value. It is entirely possible for an integer value of 10000 to result in the floating-point value 9999.99999999, or even 10000.000001. Programmers are encouraged never to expect exact values when working with floating-point numbers.
When converting strings to floating-point values, all of the strings that would parse as a valid integer are also acceptable as floats. In addition, any string that contains a decimal (.) or that contains the letter e can be parsed as a float.
<?php $f1 = (float)"+5555"; // float value: 5555.0 $f2 = (float)"-123"; // -123.0 $f3 = (float)"123.456"; // 123.456 $f4 = (float)"1.23456e2"; // 123.456 $f5 = (float)"1.234e-2"; // 0.001234 $f6 = (float)"1000000000000"; // 1e12 (one trillion) ?>
Converting from Boolean values to float is the same as first converting them to an integer and then converting them to a floating-point value. Thus, trUE evaluates to 1.0 and FALSE to0.0.
Converting from arrays, objects, or resources to floating-point values is undefined and should not be attempted or relied upon to produce predictable results.
Conversion to Strings
Integers and floating-point values are converted to strings representing their numerical values, with floating-point numbers having an exponent included for extremely large or small numbers. We will discuss means of more precisely controlling conversion in Chapter 21, "Advanced Output and Output Buffering."
Boolean values are converted to strings by having the value trUE converted to the string "1", while the value FALSE is converted to the empty string ("").
Arrays are always converted to the string value "Array", and objects are always converted to the value "Object". Resources are converted to a string, such as "Resource id #X", where X is a unique numerical identifier used by PHP to identify the resource. To see a more detailed printout of contents of an array or an object, the var_dump and related functions introduced in Chapter 1, "Getting Started with PHP," often prove useful.
NULL is converted to the empty string ("").
Conversion to Booleans
Integers and floating-point values are converted to Booleans by seeing if the value is 0 or 0.0. If so, the resulting Boolean is FALSEotherwise, it is trUE. Please note that floating-point numbers can cause troubles here.
<?php $b1 = (bool)0; // FALSE $b2 = (bool)0.0; // FALSE $b4 = (bool)-10; // TRUE $b5 = (bool)123123e-34; // TRUE $b3 = (bool)(0.4 + 0.2 0.6); // TRUE not EXACTLY 0.0 ... ?>
Strings are converted trivially to Boolean values: Empty strings and the string "0" result in FALSE, while all other strings result in TRUE.
<?php $bool1 = (bool)"happy"; // TRUE $bool4 = (bool)""; // FALSE $bool5 = (bool)"0"; // FALSE $bool2 = (bool)"TRUE"; // TRUE $bool3 = (bool)"FALSE"; // TRUE! Not empty and not "0"! ?>
Arrays with 0 elements are converted to the Boolean value FALSE. All other arrays and object instances are converted to TRUE.
Conversion to Arrays
Integers, floating-point numbers, strings, Booleans, and resources are converted to arrays by creating an array with only one element (with an index of 0), that being the value of the variable/expression.
Objects are converted to arrays by creating an array with the keys being the set of member variables on the object and the values being the value of those variables on the given object. (See Chapter 4 for more on objects.)
NULL and other unset variables convert to an empty array with 0 elements.
Conversion to Objects
Objects that are converted to objects simply return a handle to the same object. All other types have an object of type stdClass created for them. If the variable or expression was neither NULL nor unset, then the object has a member variable called scalar with the value of the previous expression or variable; otherwise, it is an empty object. Again, see Chapter 4 for more on objects.
<?php $variable = (object)234.234; echo $variable->scalar; // prints 234.234 ?>
Arrays will have named keys made into member variables of the same name in the stdClass object instance, while non-named keys (for example, those with integer values) are ignored.
Useful Type Conversion Functions
These functions all return a Boolean value that indicates whether or not the specified value was of the appropriate type.
The settype function takes two arguments: the variable to convert, and the type to which it is to be converted, which is expressed as a string. The results are the same as the explicit casts described earlier. The function returns a Boolean that indicates whether or not the conversion was successful. The variable itself is modified.
<?php $variable = 234.234; settype($variable, "string"); // $variable now has "234.234" as value, typed as string ?>