Back to the 2023 paper

Module III: Basics of Web Programming

20237m

Write a note on type conversion in PHP with example.

Worked SolutionAI Assisted

Type Conversion in PHP

Type conversion means changing a value from one data type to another. PHP supports automatic type conversion in many expressions and explicit conversion using casting.

1. Automatic type conversion

PHP may convert a value automatically when an operation requires another type.

$a = "10";
$b = 5;
result=result = a + $b;   // 15

Here the numeric string is converted to a number for the arithmetic operation.

2. Explicit type casting

A programmer can explicitly cast a value:

$x = "25";
y=(int)y = (int)x;
z=(float)z = (float)x;

Common casts include (int), (float), (string), (bool) and (array).

Example

$price = "99.50";
amount=(float)amount = (float)price;
echo $amount + 10;   // 109.5

Conclusion: PHP supports both implicit conversion and explicit casting; explicit casting is useful when the required type should be clear and controlled.

Similar questions