Why does PHP consider 0 to be equal to a string?

前端 未结 9 1803
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 02:41

I have the following piece of code:

$item[\'price\'] = 0;
/* Code to get item information goes in here */
if($item[\'price\'] == \'e\') {
    $item[\'price\'         


        
9条回答
  •  遇见更好的自我
    2020-11-22 03:16

    Your problem is the double equal operator, which will typecast the right member to the type of the left. Use strict if you prefer.

    if($item['price'] == 'e') {
        $item['price'] = -1;
    }
    

    Let's go back to your code (copied above). In this case, in most cases, $item['price'] is an integer (except when it is equal to e, obviously). As such, by laws of PHP, PHP will typecast "e" to integer, which yields int(0). (Don't believe me? ).

    To easily get away from this, use the triple equal (exact comparison) operator, which will check the type and will not implicitly typecast.

    P.S: a PHP fun fact: a == b does not imply that b == a. Take your example and reverse it: if ("e" == $item['price']) will never actually be fulfilled provided that $item['price'] is always an integer.

提交回复
热议问题