简体   繁体   中英

How can i detect if (float)0 == 0 or null in PHP

If variable value is 0 (float) it will pass all these tests:

    $test = round(0, 2); //$test=(float)0

    if($test == null)
        echo "var is null";
    if($test == 0)
        echo "var is 0";
    if($test == false)
        echo "var is false";
    if($test==false && $test == 0 && $test==null)
        echo "var is mixture";

I assumed that it will pass only if($test == 0)

Only solution I found is detect if $test is number using function is_number(), but can I detect if float variable equal zero?

Using === checks also for the datatype:

$test = round(0, 2); // float(0.00)

if($test === null) // false
if($test === 0) // false
if($test === 0.0) // true
if($test === false) // false

使用3个等号而不是2个来测试类型:

if($test === 0)

If you use=== instead of == it will compare as well as get the data types errors manage...Can you post your answer while using === ? Please check the difference between this two here

When comparing values in PHP for equality you can use either the == operator or the === operator. What's the difference between the 2? Well, it's quite simple. The == operator just checks to see if the left and right values are equal. But, the === operator (note the extra “=”) actually checks to see if the left and right values are equal, and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM