
Last week we went over how to check types in PHP. However, what happens if you have a different type than you require for your script? Well, it’s also possible to convert a variable to a different type.
Since PHP doesn’t support specifying the type when creating a variable (like other programming languages require), it is possible that you will end up with a variable of the wrong type. Converting a variable to a different type is simple, and there are two possible ways to do it.
The first method of converting a variable between types is called type casting. Here’s the basic syntax:
[code='php']$foo = 'foo';
$bar = (type) $foo;[/code]
Where type could be int, bool, float, string, array, object or unset. Basically, this would convert $foo to the type in parenthesis that precedes it in the value of another variable. Let’s look at an example, converting a numeric string to an integer.
[code='php']$number = '10';
var_dump(is_numeric($number)); // bool(true)
var_dump(is_int($number)); // bool(false)
$number = (int) $number;
var_dump(is_int($number)); // bool(true)[/code]
The other method of converting between types is by using the function settype(). You pass the variable you want converted, and the type you want it converted to, and it will convert it. The first parameter is the variable you want to convert, the second parameter is a string, of either int, bool, float, string, array, object or null. Let’s look at the above example again, except using settype() instead of type casting.
[code='php']$number = '10';
var_dump(is_numeric($number)); // bool(true)
var_dump(is_int($number)); // bool(false)
settype($number, 'int');
var_dump(is_int($number)); // bool(true)[/code]
There you have it, two viable options for converting variables to a different type.




