Type casting changes a value from one type to another. It helps when you want to treat data in a specific way.
Type casting syntax in PHP
(type) $variable;
Replace type with the desired type like int, float, string, bool, array, or object.
Put the type in parentheses before the variable you want to convert.
$num = (int) "123";false.$flag = (bool) 0;$price = (float) "12.99";$obj to an array.$arr = (array) $obj;This program shows how to convert a string to float, then to int, then back to string, and finally to boolean. It prints each step to see the changes.
<?php // Original string $priceString = "19.99"; // Convert string to float $priceFloat = (float) $priceString; // Convert float to int $priceInt = (int) $priceFloat; // Convert int to string $priceStr = (string) $priceInt; // Convert int to boolean $isAvailable = (bool) $priceInt; // Print all values print("Original string: $priceString\n"); print("Float value: $priceFloat\n"); print("Integer value: $priceInt\n"); print("String value: $priceStr\n"); print("Boolean value: " . ($isAvailable ? 'true' : 'false') . "\n"); ?>
When casting to int, decimals are removed (not rounded).
Casting to bool makes zero, empty strings, and empty arrays become false, everything else is true.
Be careful when casting objects to arrays and vice versa, as it changes how you access data.
Type casting changes data from one type to another using (type) before a variable.
Common types are int, float, string, bool, array, and object.
Use type casting to make sure your data works the way you want in your program.