Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
mrfazolka Avatar asked Jul 30 '14 13:07

mrfazolka


People also ask

Is 0 considered null in PHP?

PHP considers null is equal to zero.

How do you check if a number is a float in PHP?

The is_float() function checks whether a variable is of type float or not. This function returns true (1) if the variable is of type float, otherwise it returns false.

Is 0 a float value?

A floating point number, is a positive or negative whole number with a decimal point. For example, 5.5, 0.25, and -103.342 are all floating point numbers, while 91, and 0 are not. Floating point numbers get their name from the way the decimal point can "float" to any position necessary.

Is zero true or false in PHP?

0 is the integer value of zero, and false is the boolean value of, well, false. To make things complicated, in C, for example, null, 0, and false are all represented the exact same way.


2 Answers

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
like image 91
Markus Kottländer Avatar answered Nov 14 '22 23:11

Markus Kottländer


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

if($test === 0)
like image 2
ksealey Avatar answered Nov 14 '22 22:11

ksealey