Type Conversion in PHP
How to do Type Conversion in PHP?
Type conversion is nothing but data type change of a certain variable from one type to another. Such manual over riding of data types is called Type Casting.
PHP will automatically convert one type to another whenever possible. For example if you assign a string value to variable, this variable becomes a string variable. Sometimes automatic type conversion will lead to unexpected results. For example, calling "print" on an array makes PHP to print "Array" instead of array elements. PHP does not automatically convert the array to a string of all its elements.
If you want to get a type of a variable, you can use gettype() function
The above code will print the type of variable $var1.
If you want to permanently change type of variable, you can use settype() function
$var1 = "5bar"; // string
$var2 = true; // boolean
settype($var1, "integer"); // $var1 is now set to 5 (integer)
settype($var2, "string"); // $var2 is now set to "1" (string)
In the above example $var1 is assigned to string value so it is a string variable and $var2 holds boolean value so it is a boolean variable. Now $var1 is forced to type cast to integer and $var2 is forced to type cast to string by using settype function.
If you want to change type temporary, ie, want to use inside an expression, you can use type casting
where type is a type of variable you wish to cast to. Examples are:
$var1 = 12.2; // double
$var2 = "pre"; // string
$var3= 10; //integer
$var4=(string)$var1; // $var1 is now set to 12.2 (string)
$var5=(boolean)$var2; // $var2 is now set to 1 (boolean)
$var6=(double)$var3;// $var3 is now set to 10(double)
Here $var1 is converted to type string, $var2 is converted to type boolean and $var3 is converted to type double.
It is important to know that most of data type conversions can be done by on its own and some conversions can lead to loss of information. Consider an example of converting a float value to integer will lead to loss of information.