PHP CHAPTER 10

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

PHP Syntax
$number = (int)$value;
💻

Example

PHP Example
<?php

$value = "25";
$number = (int)$value;

echo $number + 5;

?>
🔍

Example Explained

The string 25 is converted into integer 25 before addition.
🚀

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.

Open Coding Lab →