Type Casting
Convert data from one type to another in PHP — (int), (float), (string), (bool) casts, form input handling, and professional interview answers.
Convert Data from One Type to Another in PHP
Estimated Reading Time: 8–10 minutes
Welcome
Imagine you're building an online shopping application.
A customer enters the product quantity in a form.
Although the user enters 5, PHP receives it as text because all form data is submitted as strings.
Now you need to calculate the total price.
How can PHP treat "5" as the number 5?
This is where Type Casting becomes useful.
Type casting allows you to convert a value from one data type to another so that your application can process data correctly.
What is Type Casting?
Type Casting is the process of converting a value from one data type to another.
For example, you can convert:
- String → Integer
- Integer → Float
- Float → Integer
- Integer → String
- Boolean → Integer
This helps PHP perform calculations, comparisons, and data processing correctly.
Why Do We Need Type Casting?
Consider a food delivery application.
A customer enters the quantity of pizzas as:
"3"
Since form input is received as a string, multiplying it directly with the price may not always behave as expected when dealing with mixed data.
By converting it into an integer, you ensure that mathematical operations are performed correctly.
Type casting improves data accuracy and prevents unexpected results.
Common Type Casts in PHP
| Type Cast | Description | Example |
|---|---|---|
| (int) | Convert to Integer | (int)"100" |
| (float) | Convert to Float | (float)"99.95" |
| (string) | Convert to String | (string)100 |
| (bool) | Convert to Boolean | (bool)1 |
| (array) | Convert to Array | (array)$value |
| (object) | Convert to Object | (object)$array |
These casts tell PHP how you want a value to be interpreted.
Integer Type Casting
<?php$quantity = "5";$quantity = (int) $quantity;echo $quantity;?>
Output
5
Here, the string "5" is converted into the integer 5. Now it can safely participate in mathematical calculations.
Float Type Casting
<?php$price = "1499.99";$price = (float) $price;echo $price;?>
Output
1499.99
This is useful when working with prices, taxes, and discounts.
String Type Casting
Sometimes numbers need to become text.
<?php$orderId = 1056;$orderId = (string) $orderId;echo $orderId;?>
This is useful when displaying values or exporting data.
Boolean Type Casting
<?php$status = 1;$status = (bool) $status;var_dump($status);?>
Output
bool(true)
Boolean casting is commonly used while validating conditions and permissions.
Real-World Example
Imagine you're building an online shopping cart.
The quantity entered by the customer comes from an HTML form.
<?php$productPrice = 1500;$quantity = "3";$total = $productPrice * (int)$quantity;echo "Total Amount: ₹" . $total;?>
Output
Total Amount: ₹4500
By converting the quantity into an integer, PHP performs the calculation correctly.
Automatic Type Conversion
PHP is a loosely typed language. In many situations, PHP automatically converts data types.
Example:
<?phpecho "5" + 10;?>
Output
15
PHP automatically converts "5" into an integer before performing the addition.
Although PHP can do this automatically, explicit type casting often makes your code clearer and easier to understand.
Best Practices
- Use explicit type casting when the expected data type is known.
- Validate user input before casting.
- Cast values before performing calculations.
- Keep your code readable by avoiding unnecessary casts.
- Prefer explicit conversions in production code.
Common Mistakes
Assuming all input is numeric
Remember that data from forms and URLs usually arrives as strings.
Ignoring invalid values
(int)"ABC"
This returns:
0
Always validate input before converting it.
Overusing Type Casting
Don't cast every variable unnecessarily. Use it only when a conversion is actually required.
Hands-on Exercise
Task: Create variables Price = "2500" and Quantity = "4". Convert both values into integers. Calculate the total amount. Display the result.
Challenge: Create variables for Product Price and Discount Percentage. Convert both values appropriately and calculate the final payable amount.
<?php$price = "2500";$quantity = "4";// TODO: cast and calculate total// Challenge: product price + discount percentage?>
Summary
- Type Casting converts one data type into another.
- PHP supports casting to Integer, Float, String, Boolean, Array, and Object.
- Form data is usually received as strings.
- Explicit casting improves code readability and accuracy.
- Always validate data before converting it.
Key Takeaways
- Type Casting ensures values are treated as the correct data type.
- Use (int), (float), (string), and (bool) when appropriate.
- PHP also performs automatic type conversion in some cases.
- Explicit casting makes applications more predictable.
- Correct data types lead to fewer bugs and more reliable applications.
Interview Questions & Professional Answers
Q1What is Type Casting in PHP?
Professional Answer
Type Casting is the process of converting a value from one data type to another. It helps ensure that PHP processes data correctly, especially when working with user input, APIs, databases, or calculations.
Example
$age = "25";$age = (int)$age;
Interview Tip: Mention that HTML forms always send data as strings, making type casting a common requirement.
Q2Why is Type Casting important in PHP?
Professional Answer
Type casting improves data accuracy and prevents unexpected behavior. It ensures that values are treated as the correct data type before calculations, comparisons, or business logic are executed.
Real-World Example: In an e-commerce application, product quantity received from a form should be converted into an integer before calculating the total price.
Q3What is the difference between Automatic Type Conversion and Explicit Type Casting?
Professional Answer
Automatic Type Conversion (Type Juggling) happens when PHP converts values automatically based on the operation being performed. Explicit Type Casting occurs when the developer manually converts the data type using casts such as (int) or (float). Explicit casting makes the code more readable and predictable.
Q4What types can be cast in PHP?
Professional Answer
PHP supports casting to Integer, Float, String, Boolean, Array, and Object. Each cast serves a different purpose depending on the application's requirements.
Q5What precautions should developers take while using Type Casting?
Professional Answer
Developers should always validate user input before casting. Casting invalid data can lead to unexpected results, such as converting non-numeric text to 0. Combining validation with explicit type casting results in more reliable and secure applications.
Interview Tip: Mention validation functions like filter_var() or is_numeric() when discussing user input. This demonstrates awareness of secure coding practices.
What's Next?
Now that you know how to convert data between different types, it's time to learn how PHP automatically converts values behind the scenes.
In the next lesson, Type Juggling (Automatic Type Conversion), you'll discover how PHP decides data types during calculations and comparisons, and how understanding this behavior helps you avoid subtle bugs in real-world applications.