Why does this always return true
:
$s = \'334rr\';
$i = (int)$s;
if ($i == $s) {
echo true;
} else {
echo false;
}
If I ec
From the manual:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
So: ($i == $s)
is the same as ($i == (int)$s)
for the values you've given.
Use ===
to avoid type-juggling.
Comparing strings to an int is not recommended. You should use the ===
instead which will verify the same data type as well as the same value.
PHP converts the $s string to an integer when comparing to another integer ($i). It basically does this (well, i don't know what it does internally, but it boils down to this):
if($i == (int) $s)
Which makes the statement true
When compare string with integer using ==
, string will try to case into integer.
Try this
$s = '334rr';
$i = intval($s);
if ($i == $s) {
echo true;
} else {
echo false;
}