In weakly typed languages, type coercion is where a data type is converted by the interpreter from one type to another (such as a string to an integer). This most often occurs in comparing two values. Use for questions where type coercion is an issue with your code.
Type coercion occurs in weakly typed languages (like javascript or php). Consider this PHP code
$x = '1'; // string
$y = $x + 1;
echo $y;
$x
is a string, but we call it like an integer when setting $y
. So the PHP engine coerces '1'
(which is a string data type) into an integer for the purposes of math. As such, the script echoes 2
because the string 1
can be coerced neatly into integer 1
. But not everything is so neatly handled
$x = 'a';
$y = $x + 1;
var_dump($y);
Now, 'a'
is not readily coerced into a number. As such, we get back integer(1)
because PHP coerces strings to 0
(modern PHP emits a E_WARNING
that this is happening).
This most often rears itself in doing comparisons. Consider this code
$x = 'Something';
echo (strpos($x, 'Some') != false) ? 'Found it!' : 'Did not find it';
This script doesn't run like we expect. It tells us it didn't find it when we know it should have found it. The problem is that strpos can return a boolean false
or the position of where it found the match. In this case, the match was at position 0
. Our test then becomes
if( 0 == false )
Type coercion nails us here because 0
is coerced into false
in PHP. PHP and Javascript both have a workaround for this, however. We can use ===
and !==
to tell the interpreter to not coerce before comparing. If we tell PHP not to coerce the 0
, we get back the results we expect
echo (strpos($x, 'Some') !== false) ? 'Found it!' : 'Did not find it';