开发者

float 0 returns as empty string in php

could anyone explain why float 0 is empty? The code below will show "weird"

$empty = (float)"0";
if($empty == "")
  echo "weird";

On the other hand if i were to the cod开发者_如何学Ce below, it will never show "weird".

$empty = (float)"0.01";
if($empty == "")
  echo "weird";


This is because in PHP the following expressions are true:

0 == ""
0.0 == ""

not because $empty here is the empty string "".

You can perform a typed equality check using ===, and these expressions will appear false, as expected:

0 === ""
0.0 === ""


That's not weird at all, that's expected. Remember, in PHP 0 evaluates to FALSE, as does an empty string. To avoid this, use === which tests for strict equality ( a === b means, "does a == b and am I comparing apples to apples", while a == b means "do these things have the same value?" (it doesn't matter if I am comparing apples and goats))

Try this:

$empty = (float)"0";
if($empty === "")
  echo "weird";


Because that's how loose comparison works in PHP. http://php.net/manual/en/types.comparisons.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜