Imran Qamer
Imran Qamer

Reputation: 2265

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";
}

Upvotes: 2

Views: 14585

Answers (5)

Anthony Rutledge
Anthony Rutledge

Reputation: 7564

Using PHP's language construct isset() will report true to let you know if the value is NOT null. You can also use is_null(), but isset() tends to be reported as being faster.

if (isset($var)) {
    echo 'It is something.';
} else {
    echo 'It is nothing.';
}

or

if (!is_null($var)) {
    echo 'It is something.';
} else {
    echo 'It is nothing.';
}

or

if ($var !== null)) {
    echo 'It is something.';
} else {
    echo 'It is nothing.';
}

Upvotes: 2

Dan Ionescu
Dan Ionescu

Reputation: 3423

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

Upvotes: 11

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

You can use the following solution (using is_null and ===):

if (is_null($moon)) {
    echo "its null";
} elseif ($moon === 0) {
   echo "its zero"; 
} elseif ($moon == 0) {
   echo "its zero (string)";
} else {
   echo "another value";
}

You can use the function is_null.

explanation using is_null:

$val1 = NULL;
$val2 = 0;
var_dump(is_null($val1)); //true
var_dump(is_null($val2)); //false

explanation using ===:

$val1 = NULL;
$val2 = 0;
var_dump($val1 === 0); //false
var_dump($val2 === 0); //true

Demo: https://ideone.com/TpPQQi

Upvotes: 2

Daniel_ZA
Daniel_ZA

Reputation: 574

As already mentioned you can use the is_null() function.

You can use this function in conjunction with the ! operator in your if() statement as follows:

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

Upvotes: 1

Fabio
Fabio

Reputation: 23480

You might want to use three equal to see if the given value is identical so

$moon = 0;
if($moon === 0) {
    echo 'its zero';
} else {
    echo 'is null';
}

You can check more about comparison operators here

Upvotes: 2

Related Questions