PHP  type  casting

php is a loosely typed language:


converting an expression of a given type into another type is known as type-casting.

syntax:

                $variable_name = (type_name) cast_expression 
  • type_name - is a type.
  • cast_expression - is a value to be converted to that type.

the cast_expression is converted as though it had been assigned to a variable of type type_name.

here is the full list of casts that you can use in php.

functiondescription
(int) value or (integer) valuereturns value cast to an int
(float) valuereturns value cast to a float
(string) valuereturns value cast to a string
(bool) value or (boolean) valuereturns value cast to a boolean
(array) valuereturns value cast to an array
(object) valuereturns value cast to an object

you can also cast a value to an integer, floating-point, or string value using three php functions:

functiondescription
intval( value )returns value cast to an integer
floatval( value )returns value cast to a float
strval( value )returns value cast to a string
   <?php
   
             $str = "23232";
             
             $x   = "34.34";
             
             $y   = "";
             
              var_dump((int)$str);
              
              echo "<br/>";
              
              var_dump((float)$str);
              
              echo "<br/>";
              
              var_dump((bool)$x);
              
              echo "<br/>";
              
              var_dump((string)34343.3434);  echo "<br/>";
              
              var_dump((bool)45454);
              
              var_dump(intval('343434')); echo "<br/>";
              
              var_dump(floatval(22323));  echo "<br/>";
              
              var_dump(strval(2323.22323)); 
   
   ?>

type testing

you can also test a variable for a specific data type using php type testing functions:

functiondescription
is_int( value )returns true if value is an integer
is_float( value )returns true if value is a float
is_string( value )returns true if value is a string
is_bool( value )returns true if value is a boolean
is_array( value )returns true if value is an array
is_object( value )returns true if value is an object
is_null( value )returns true if value is null
    <?php
    
          $x = 3434;   $y= 343.3434;  $str= "this is name";
          
          $bool = true;  $nu = null;
          
          
          echo   "x is integer = ". is_int($x);
          
          echo   "y is float   =".  is_float($y)."<br/>";
          
          echo   "str is string =". is_string($str)."<br/>";
          
          echo   "bool is boolean =".is_bool($bool)."<br/>";
          
          echo   "nu is null =".is_null($nu)."<br/>";
          
          echo   "x is integer =".is_float($x);
          
    ?>

note: 1 value for true and 0 for false