Reputation: 2265
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
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
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
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
Upvotes: 2
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