type casting can cause a variable's value to be treated as a specific type.
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.
In the following example, a variable's value is cast to various different types at the time that the value is displayed:
<?PHP $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
.
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 |
PHP automatically converts one type of variable to another whenever possible.
<?PHP
$mystring = "12";
$myinteger = 20;
print $mystring + $myinteger;
?>
The code above generates the following result.
That script will output 32.
Converting from a boolean to a string will produce a 1 if the boolean is set to true, or an empty string if false.
Consider this script:
<?PHP $bool = true; print "Bool is set to $bool\n"; $bool = false; print "Bool is set to $bool\n"; ?>
The code above generates the following result.
We can solve this problem by typecasting.
<?PHP $bool = true; print "Bool is set to $bool\n"; $bool = false; print "Bool is set to "; print (int)$bool; ?>
The code above generates the following result.
This time the script outputs 1 and 0 as we wanted.