PHP Data type conversion

Type casts in PHP are very similar to those in C: Add the bracketed parentheses before the variable you want to convert:

$foo = 10; // $foo is an integer
$Bar = (boolean) $foo; // $bar is a boolean type

Allowed casts are:

  1. (int) or (integer) - Convert to Integer
  2. (bool) or (boolean) - Convert to Boolean
  3. (float) or (double) or (real) - convert to float
  4. (string) - Convert to string
  5. (array) - Convert to an array
  6. (object) - Convert to object

In addition, to restore a variable to a string, you can also place the variable in double quotation marks:

$foo = 10; // $foo is an integer
$str = " $foo "; // $str as a string

Type Juggling

PHP does not need(or supports) explicit type definitions in the variable definition, which is determined by the context in which the variable is used:

$foo = " 0 "; // $foo is a character
$foo = $foo + 2; // $foo is now an integer with a value of 2
$foo = $foo + 1.3; // $foo is a floating point type: 3.3
$foo2 = 5 + " 10 Little Piggies "; 
// $foo2 is an integer, refer to the following extended reading section

Extended Reading

When a string is evaluated as a number, the type and value of the result are determined according to the following rules:

  1. If any of the characters ".", "E" or "E" are included, the string is evaluated as a float, otherwise it is treated as an integer
  2. This value is determined by the top-most part of the string. If the string starts with valid numeric data, use that number as its value; otherwise, the value is 0(zero). Legitimate digital data begins with an optional sign followed by one or more digits(optionally including a decimal fraction) followed by an optional exponent. The exponent is an "e" or "E" followed by one or more digits


$foo = 1 + " 10.5 "; // $foo as Float: 11.5
$foo = 1 + " -1.3e3 "; // $foo is a floating point type: -1299
$foo = 1 + " bob-1.3e3 "; // $foo is an integer: 1
$foo = 1 + " bob3 "; // $foo is an integer: 1
$foo = 1 + " 10 Small Pigs "; // $foo as Integer: 11
$foo = " 10.0 pigs " + 1; // $foo as Float: 11


As mentioned earlier, PHP is a loose type of language, do not have to use the variable to do a special definition, which gives the preparation of the program a great deal of flexibility and convenience. But in the process of writing, we need to know what kind of variables they use, because the variable always has a type corresponding to it. Although almost all types of free conversion can be done, if the free use or conversion variable type, may lead to some potential errors.

Copyright 2014-2017 by All Rights Reserved.