Type Conversions

Table of Contents

Type Conversions

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:

  • Binary arithmetic operators If one operand is an integer and the other is a floating-point number, then the first is also evaluated as a float. If one is a string and the other an integer, PHP converts the string to an integer before evaluating both operands as integers.

  • Boolean expressions and expression operators For those places where an expression must be evaluated as a Boolean, PHP converts the result of the expression to a Boolean before continuing.

  • Certain methods that expect strings Certain methods and operatorsecho, print, or the string concatenation operator (.)expect their arguments or operands to be strings. In these cases, PHP tries its best to convert non-string variables to strings.

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:

  • (int), (integer) This casts to an integer.

  • (float), (double), (real) This casts to a floating-point number.

  • (string) This casts to a text string.

  • (bool), (boolean) This casts to a Boolean value.

  • (array) This casts to an array.

  • (object) This casts to an object.

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.


  // don't worry about the $_POST array  you'll see
  // it again soon!
  $quantity_string = $_POST['quantity_desired'];

  $quantity_desired = (int)$quantity_string;


Next, we will show more examples and discuss the specifics of these conversions.

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

You can convert values to integers explicitly by using the (int) or (integer) casts, or the intval function.

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


  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.)


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.


  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.

NULL always converts to the integer value 0.

Conversions to Floating-Point Numbers

Variables and expressions can be converted to the floating-point type by using the (float), (double), or (real) type casts, or by calling the floatval function.

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.


  $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.

NULL always converts to the floating-point value 0.0.

Conversion to Strings

You can convert variables to strings by using the (string) type cast or by calling the strval function. Additionally, you can convert variables to strings by enclosing them in double quotes.

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

You can convert variables to Booleans by using the (bool) or (boolean) type casts.

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.


  $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.


  $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.

NULL and unset variables are assigned the value FALSE.

Conversion to Arrays

You can convert a variable or expression to an array by using the (array) type cast or the array function, the latter of which is the same as creating a new array.

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

You can convert a variable or expression to an object by using the (object) type cast.

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.

  $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

In addition to the various type casts and other methods we have mentioned, there are a number of useful functions to help us understand types and variables in PHP.


There are a number of useful helper routines that will tell us if a variable is of a particular type, with the name corresponding to the obvious type. The methods are as follows:

  • is_integer

  • is_float

  • is_numeric (returns trUE if the argument is a float or integer or a numeric string)

  • is_string

  • is_bool

  • is_array

  • is_object

  • is_null

These functions all return a Boolean value that indicates whether or not the specified value was of the appropriate type.


gettype is a very useful routine that tells you what type PHP currently considers a variable or expression. It returns the following values:

  • "boolean"

  • "integer"

  • "double" (note, for historical reasons, float is not returned!)

  • "string"

  • "array"

  • "object"

  • "resource"

  • "NULL"

  • "unknown type"

In general, use of this function is discouraged in favor of the various is_type functions.


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.

  $variable = 234.234;
  settype($variable, "string");

  // $variable now has "234.234" as value, typed as string

In general, use of this function is discouraged in favor of the casting functions.

Table of Contents
© 2000- NIV