0
0
PHPprogramming~5 mins

Type coercion in operations in PHP

Choose your learning style9 modes available
Introduction
Type coercion helps PHP automatically change data types so operations work smoothly without errors.
When adding a number and a string that contains a number.
When comparing values of different types, like a number and a string.
When mixing booleans with numbers in calculations.
When using variables from user input that might be strings but need to act like numbers.
Syntax
PHP
$result = $value1 + $value2;
PHP automatically converts types when using operators like +, -, *, /.
Strings with numbers convert to numbers; non-numeric strings convert to 0.
Examples
Adds an integer and a numeric string. PHP converts the string "10" to number 10.
PHP
$sum = 5 + "10";
echo $sum;
String starts with a number, so PHP uses 5 and adds 3 to get 8.
PHP
$result = "5 apples" + 3;
echo $result;
Boolean true converts to 1, so 1 + 2 equals 3.
PHP
$value = true + 2;
echo $value;
Loose comparison converts string to number, so they are equal.
PHP
$compare = ("5" == 5);
echo $compare ? 'true' : 'false';
Sample Program
This program shows how PHP changes types automatically when adding or comparing different types.
PHP
<?php
$a = "7";
$b = 3;
$c = $a + $b;
echo "Sum: $c\n";

$d = "hello" + 4;
echo "Result: $d\n";

$e = false + 10;
echo "Boolean sum: $e\n";

if ("10" == 10) {
    echo "Comparison is true\n";
} else {
    echo "Comparison is false\n";
}
?>
OutputSuccess
Important Notes
Non-numeric strings convert to 0 when used in math operations.
Use === for strict comparison to avoid type coercion surprises.
Type coercion can be helpful but sometimes causes unexpected results, so be careful.
Summary
PHP changes data types automatically in operations to avoid errors.
Strings with numbers become numbers; booleans become 0 or 1.
Use strict comparison (===) to check both value and type.