Search code examples
phpif-statementnullzero

How to differentiate a value is zero or NULL in php?


I have a variable e.g $moon

In some cases its value is

$moon=0;

In other cases its value is

$moon=NULL;

Now in if clause how can i differentiate between these values?

My code is

if($moon==0 && !empty($moon)){
    echo "its zero";        
}else{
    echo "its null";
}

it always shows "its zero"

I also tried

if($moon==0 && $moon!=NULL){
    echo "its zero";        
}else{
    echo "its null";
}

Solution

  • to check for null use :

    if (is_null($moon))
    

    to check for integer 0 use:

    if ($moon === 0)
    

    to check for integer 0 or string "0"

    if ($moon == '0')
    

    I have to add that php will consider any string equals with number 0 when using "==":

    $moon = "asd";
    
    if ($moon == 0) // will be true