Strange error in PHP | number zero (0) evaluates to true against a string in PHP

Reproducing the error (see solution below):
Take a look at this weird error below:

$int_zero="reset";
$str_zero="0";
$int_zero=intval($str_zero);
if ($int_zero == "reset"){

echo "equals reset\n";

} else {

echo "equals something else\n";

}

echo $int_zero."\n";

Output:

equals reset
0

So strange n'est pas? This should not happen. At first, I thought it had to do with the intval or floatval functions since I tried both and got the same result. But it turns out this is wrong. For example I created a function that returns 0 without the use of intval when it is a zero.

Replace intval, still an error

function intval_v2($str){

$str = trim($str);
if (preg_match("/^(\s|0|\.)*$/",$str)){

return 0;

} else {

return intval($str);

}

}

When I use this function instead of intval, I still get the same bad result. In fact if I do the following I get the same result.

Don't use intval...still..bzzzz...wrong

$int_zero=0;
$some_num=3;
$some_num = $int_zero;
if ($some_num == "whatever it does not matter"){
echo "equals whatever it does not matter\n";
} else {
echo "equals a number\n";
}
echo "$some_num\n";

Output:

equals whatever it does not matter
0

The work around...


The way around it is to use a strict comparison known as the triple equal operator (===) the problem is the zero (0) not the intval or floatval functions.

$int_zero=0;
$some_num=3;
$some_num = $int_zero;
if ($some_num === "whatever it does not matter"){
echo "equals whatever it does not matter\n";
} else {
echo "equals a number\n";
}
echo "$some_num\n";

Output:

equals a number
0
PHP has lost major cool points from me this day.

comments powered by Disqus