0
0
PHPprogramming~5 mins

Type casting syntax in PHP

Choose your learning style9 modes available
Introduction

Type casting changes a value from one type to another. It helps when you want to treat data in a specific way.

When you get a number as a string but want to do math with it.
When you want to make sure a value is a boolean before checking it.
When you want to convert a float to an integer to remove decimals.
When you want to turn an array into an object or vice versa.
Syntax
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.

Examples
This converts the string "123" to the integer 123.
PHP
$num = (int) "123";
This converts the number 0 to the boolean false.
PHP
$flag = (bool) 0;
This converts the string "12.99" to the float 12.99.
PHP
$price = (float) "12.99";
This converts an object $obj to an array.
PHP
$arr = (array) $obj;
Sample Program

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
<?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");
?>
OutputSuccess
Important Notes

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.

Summary

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.