PHP Data Type Cast

Description

type casting can cause a variable's value to be treated as a specific type.

Syntax

Placing the name of the desired data type in parentheses before the variable's name.

variableName1 = (newType)variableName2;

or

variableName1 = (newType)variableName1;

The second form cast to itself.

Example

In the following example, a variable's value is cast to various different types at the time that the value is displayed:


<?PHP/*from  ww  w  .  ja va2 s  .co m*/
       $test_var = 8.23; 
       echo $test_var;             // Displays "8.23" 
       echo (string)$test_var;     // Displays "8.23" 
       echo (int) $test_var;       // Displays "8" 
       echo (float) $test_var;     // Displays "8.23" 
       echo (boolean) $test_var;   // Displays "1"   
?>

The code above generates the following result.

$test_var's type isn't changed at any point. It remains a floating - point variable, containing the value 8.23.

Casting list

Here's the full list of casts that you can use in PHP:

Function Description
(int) value or (integer) valueReturns value cast to an integer
(float) valueReturns value cast to a float
(string) value Returns value cast to a string
(bool) value or (boolean) value Returns value cast to a Boolean
(array) valueReturns value cast to an array
(object) value Returns value cast to an object




















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone