PHP Casting
Type casting converts a value from one type to another.
What is it?
Type casting converts a value from one type to another.
Why do we use it?
Form values often arrive as strings and may need to be converted to numbers.
How does it work?
PHP converts the value using explicit casts such as (int), (float), (string) and (bool).
Syntax
$number = (int)$value;
Example
<?php $value = "25"; $number = (int)$value; echo $number + 5; ?>
Example Explained
More Examples
<?php $price = "99.50"; $price = (float)$price; echo $price; ?>
⚠️ Important Rules
Validate external input before relying on the converted result.
❌ Common Mistakes
Casting invalid text and expecting a meaningful number.
🌍 Real-World Use
Form processing and API data often require type conversion.
📝 Practice Exercise
Convert three string numbers into integers and calculate their total.
💻 Try It Yourself
Write and run this PHP lesson inside the AIFA Coding Lab.