PHP is a loosely typed language and assigns types to variables depending what is assigned to it. Variables coming from get/post and cookies etc are generally cast as strings rather than other types and there are often other times when you need to specifically cast a type in PHP as e.g. an integer. This post looks at how to type cast in PHP and some of the results than can come about from type casting.
There are two ways to cast a variable in PHP as a specific type: using the settype() function, or using (int) (bool) (float) etc. Using the settype function you can do this:
settype($foo, "array"); settype($foo, "bool"); settype($foo, "boolean"); settype($foo, "float"); settype($foo, "int"); settype($foo, "integer"); settype($foo, "null"); settype($foo, "object"); settype($foo, "string");
Using (int) etc you can do this instead:
$foo = (array)$foo; $foo = (b)$foo; // from PHP 5.2.1 $foo = (binary)$foo; // from PHP 5.2.1 $foo = (bool)$foo; $foo = (boolean)$foo; $foo = (double)$foo; $foo = (float)$foo; $foo = (int)$foo; $foo = (integer)$foo; $foo = (object)$foo; $foo = (real)$foo; $foo = (string)$foo;
An example of this in action is as follows, where $foo starts off as a string value and is then cast into an integer:
$foo = '1'; echo gettype($foo); // outputs 'string' settype($foo, 'integer'); echo gettype($foo); // outputs 'integer'
The equivilent way of doing this with (int) would look like this instead:
$foo = '1'; echo gettype($foo); // outputs 'string' $foo = (int)$foo; echo gettype($foo); // outputs 'integer'
I often find the (int) function useful when needing to output the value of a boolean value when debugging and testing. You can do this for example:
$foo = true; echo (int)$foo; // outputs 1 $foo = false; echo (int)$foo; // outputs 0
Without the type casting, echoing $foo when it’s false won’t show anything.
This post will be followed by a second next week looking at the results of type casting conversion, such as when you convert a string to an integer with PHP.