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

20,022

Solution 1

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

Solution 2

Use 3 equal signs rather than two to test the type as well:

if($test === 0)
Share:
20,022
mrfazolka
Author by

mrfazolka

Like Nette FW(great php fw), Java, .NET, AI. Have experience with Oracle 11g db, OpenCV, android, neural networks, InterSystem Caché db, less.

Updated on July 09, 2022

Comments

  • mrfazolka
    mrfazolka almost 2 years

    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?

  • scragar
    scragar almost 10 years
    0 == 0.0 && 0 !== 0.0 Floats and ints are non-comparable with triple equals.
  • Mehravish Temkar
    Mehravish Temkar over 7 years
    Had trouble checking whether my float variable's value was 0 or null! This helped thanks!