Type conversion is nothing but change the data type of a variable one type to another. PHP automatically convert data type one to another whenever possible. For example if you assign string value into a variable then the variable automatically become into string variable . But sometime this automatic type conversion is lead unexpected result. For that case we need to convert the data type by manually. I hope you will enjoy it.
<?php /** * @Author: Sohel Rana * @URL: http://www.sohelranabd.com * @Description: This is simple example of type conversion */ $stringVar = "10 Hello World"; //Integer variable echo gettype($stringVar); // Knowing the data type of $stringVar $intVar = (int)$stringVar; //Converting into integer echo $intVar;
This is called the type casting. But if you permanently change the type then you need to use “settype()” function.
$stringVar = "10 Hello World"; //Integer variable settype($stringVar,'integer'); // permanently change the type echo gettype($stringVar); // Knowing the data type of $stringVar
This is the simple way to change the type. Remember this is also applicable for all data types (boolean,float, object, array, etc) of php.