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) value | Returns value cast to an integer |
(float) value | Returns 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) value | Returns value cast to an array |
(object) value | Returns value cast to an object |