·  PHP – Syntax – Datatypes – Type casting


- Info:

  - Type casting means converting values from one datatype to another.

  - This can be done implicitly or by using Type Casting Operators.







Cast to Array


(bool) or (boolean)

Cast to Boolean


(int) or (integer)

Cast to Integer



Cast to 64-bit Integer



Cast to Object


(real) or (double) or (float)

Cast to Float



Cast to String


- Example:

  - Create PHP Console Application Test.php.





      echo (double) 13;          //13.0


      //Type casting double to integer results in integer value being rounded down.


      //Casting string to number results in 0 if string can't be interpreted as number.

      echo (int)    14.8;        //14

      echo (int)    "Hello";     //0

      echo (int)    "55";        //55


      //When casting datatype to array, value being cast becomes first element of array.

      $poeple = (array)  "John"; //Convert to array with one element.

      echo $poeple[0];           //John


      //When casting datatype to object, value becomes property of object with the name scalar.

      $obj    = (object) "Jill"; //Convert to object with property scalar.

      echo $obj->scalar;         //Jill