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

前端 未结 9 1792
佛祖请我去吃肉
佛祖请我去吃肉 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:15

    There's a rather handy method in PHP for validating a mix of "0", "false", "off" as == false and "1", "on", "true" as == true which is often overlooked. It's particularly useful for parsing GET/POST arguments:

    filter_var( $item['price'], FILTER_VALIDATE_BOOLEAN );
    

    It's not wholy relevant to this use-case but given the similarity and fact this is the result search tends to find when asking the question of validating (string)"0" as false I thought it would help others.

    http://www.php.net/manual/en/filter.filters.validate.php

提交回复
热议问题