Typecast

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

  1. Integer  using (int) or (integer)
  2. Boolean using (bool) or (boolean)
  3. Floating Number using (float)  or (real) or (double)
  4. String using (str)
  5. Array using (array)
  6. Object using (object)
  7. 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 .

Scroll to Top