Introduction
Type coercion helps PHP automatically change data types so operations work smoothly without errors.
$result = $value1 + $value2;
$sum = 5 + "10"; echo $sum;
$result = "5 apples" + 3; echo $result;
$value = true + 2; echo $value;
$compare = ("5" == 5); echo $compare ? 'true' : 'false';
<?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"; } ?>
'5' + 3?(int)'true' + 2: (int)'true' is 0 + 2 = 2 (wrong). 'true' + 2: 'true' converts to 0 + 2 = 2 (wrong). true . 2: concatenation '12' (wrong). true + 2: 1 + 2 = 3 (correct).$a = '10 apples';
$b = 5;
echo $a + $b;
$x = '5 cats';
$y = 3;
$result = $x - $y;
echo $result;
$a = '0' (string) and $b = false (boolean). Which comparison returns true when using type coercion, and which returns false when checking type strictly?Pass the test and this pattern moves unknown