PHP settype() function

Description

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//from   w  w w.j  a  v  a 2  s.c  om
         $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.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions