Type Casting
Want to ensure that a value is an integer and not a float? Or do you need to make sure you’re working with strings before proceeding?
Type casting is the name of the method used to convert values of one type to another type. Its implementation is simple, though the results can vary depending on the original type and the final type.
To perform type casting, simply put the new type in parenthesis before the value. It will look like a function with the parenthesis in the wrong place.
$x = (int) "monkey"; // 0 $x = (int) "17monkey"; // 17 $x = (string) 34.803; // '34.803' <--that's the string value, no quotes are actually added $x = (bool) "apple"; // true $x = (array) "one, two"; // array(0 => "one, two")
Here are the types you can cast to:
integer : (int), (integer) boolean : (bool), (boolean) float : (float), (double), (real) string : (string) array : (array) object : (object) null : (unset) binary : (binary) -- as of PHP 5.2.1
Keep in mind how some values translate across types. Zero for instance will become false as a boolean. What will boolean false be when type cast to a string? What do you get when you cast an array to an object?
Be sure you understand the possible results and have a look at this page in the manual about type casting. Follow the links at the end of that section for more information about the different types.
