Type casting is the process of explicitly converting a variable from one data type to another. Since PHP is loosely typed, it often does this automatically, but there are times when you need to force a specific type for security or calculation reasons.
To cast a variable, you place the name of the desired data type in parentheses before the variable you want to convert.
<?php
$x = 5; // Integer
$x = (string) $x; // Now $x is a String "5"
var_dump($x);
?>
PHP recognizes the following operators for explicit casting:
| Operator | Converts to |
|---|---|
(string) |
String |
(int) / (integer) |
Integer |
(float) / (double) |
Float |
(bool) / (boolean) |
Boolean |
(array) |
Array |
(object) |
Object |
Casting a float to an integer will always **truncate** the decimal part (it does NOT round to the nearest number).
<?php
$num = 45.89;
echo (int)$num; // Outputs: 45
?>
Converting an array to an object turns the array keys into object properties. This is very common when working with JSON data.
<?php
$userArray = ["name" => "John", "age" => 25];
$userObj = (object)$userArray;
echo $userObj->name; // Outputs: John
?>
(bool) follows the same rules as truthy/falsy values. For example, (bool)0 is false, while (bool)1 is true.
An alternative to parentheses casting is the settype() function. Unlike parentheses casting (which returns a new value), settype() modifies the original variable.
<?php
$val = "100 apples";
settype($val, "integer");
echo $val; // Outputs: 100
?>
(int) ensures your math works correctly.
(int).->).