How to Type cast variable in PHP (Type casting)?
Typecast : PHP does not support type definition of the variable. In php we never define data type while declaring the variable. In PHP variables automatically decide the data type on the basis of the value assignment.
We can cast following data type variable in php
- Integer using (int) or (integer)
- Boolean using (bool) or (boolean)
- Floating Number using (float) or (real) or (double)
- String using (str)
- Array using (array)
- Object using (object)
- Null using (unset)
For an example we are given $a=5;
we can check datatype by gettype() function gettype($a)
now if you want to typecast then you can do the following
$b= (double)$a;
/// for type cast to double
$b= (string)$a;
/// for type cast to string
$b= (integer)$a;
///for type cast to integer
$b= (bool)$a;
///for type cast to Boolean
$b= (array)$a;
///for type cast to array
/// Another type to typecast is settype()
$a=242;
settype($a,\'string\');
Note: Settype changes datatype of variable ,where as typecasting of changes datatype of new variable to which value is assign .