PHP settype() function

In this chapter you will learn:

  1. Description for PHP settype() function
  2. Syntax for PHP settype() function
  3. Parameter for PHP settype() function
  4. Return value for PHP settype() function
  5. Example - Set the type

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//  ja va 2 s  .  c  o  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.

Next chapter...

What you will learn in the next chapter:

  1. Description for PHP strval() function
  2. Syntax for PHP strval() function
  3. Parameter for PHP strval() function
  4. Return value for PHP strval() function
  5. Example - Convert class to a string
Home » PHP Tutorial » PHP Data Type Functions
PHP boolval() function
PHP floatval() function
PHP gettype() function
PHP intval() function
PHP is_array(value) function
PHP is_bool() function
PHP is_float() function
PHP is_int() function
PHP is_null() function
PHP is_numeric() function
PHP is_object() function
PHP is_resource() function
PHP is_string() function
PHP isset() function
PHP settype() function
PHP strval() function