Type Casting
Type Casting
type casting is an explicit process used to convert a variable from one data type into another data type such as integer, float, string, or boolean.
It allows the developer to have full control over the data type of a variable during program execution.
PHP Casting Operators
- (string) → Converts value into a String (text)
- (int) → Converts value into an Integer (whole number)
- (float) → Converts value into a Float (decimal number)
- (bool) → Converts value into a Boolean (true/false)
- (array) → Converts value into an Array
- (object) → Converts value into an Object
- (unset) → Converts value into NULL (deprecated, not recommended in modern PHP)
Example
// Original values
$str = "100"; // String
$float = 10.75; // Float
$int = 50; // Integer
// 1. String Casting (convert to string)
echo "String: " . (string)$int;
echo "\n";
// 2. Integer Casting (convert to integer)
echo "Integer: " . (int)$float;
echo "\n";
// 3. Float Casting (convert to float)
echo "Float: " . (float)$str;
echo "\n";
// 4. Boolean Casting (convert to true/false)
echo "Boolean: " . (bool)$int;
echo "\n";
// 5. Array Casting (convert to array)
print_r((array)$str);
echo "\n";
// 6. Object Casting (convert to object)
var_dump((object)$str);
?>