PHP Tutorial - PHP settype() function






We can use PHP's settype() function to change the type of a variable while preserving the variable's value.

Syntax

bool settype ( mixed &$var , string $type )

Parameter

ParameterMeaning
varThe variable being converted.
typenew type

Possibles values of type are:

  • "boolean" or "bool"
  • "integer" or "int"
  • "float"
  • "string"
  • "array"
  • "object"
  • "null"




Return

Returns TRUE on success or FALSE on failure.

Example

At first $test_var variable contains 1.23, a floating - point value.

Next, $test_var is converted to a string, which means that the number 1.23 is now stored using the characters 8, . , 2 , and 3.

After converting $test_var to an integer type, it contains the value 8; the fractional part of the number has been lost.

Finally, after converting $test_var to a Boolean, it contains the value true (which PHP displays as 1 ). This is because PHP converts a non - zero number to the Boolean value true.


<?PHP/*  w  w  w  .j a  va2  s . co  m*/
         $test_var = 1.23; 
         echo $test_var . "\n";         // Displays "1.23" 
         settype( $test_var, "string" ); 
         echo $test_var . "\n";         // Displays "1.23" 
         settype( $test_var, "integer" ); 
         echo $test_var . "\n";         // Displays "8" 
         settype( $test_var, "float" ); 
         echo $test_var . "\n";         // Displays "8" 
         settype( $test_var, "boolean" ); 
         echo $test_var . "\n";         // Displays "1"   
?>

The code above generates the following result.