10minute
10minute

Reputation: 5

How to distinguish between "0" and null?

I have a database with some football scores (goal differences).

p12_score1 contains 3, -2, 0 and NULL

All I want to do is to print all score differences (including 0) and ignore the row that has no value (NULL in mysql). However is_null also considers the value 0 a null and won't print it.

IF(!$p12_score1==NULL){
$equal[] = $p12_score1;
}
else {
echo "null";
}
print_r ($equal);

Upvotes: 0

Views: 229

Answers (6)

Pitchinnate
Pitchinnate

Reputation: 7556

The function is_null should work. Another option is is_int. I tried both and both work correctly.

Upvotes: 0

Benjamin Paap
Benjamin Paap

Reputation: 2759

If you want to do this in PHP instead of sql you have to change your code to this:

IF (!$p12_score1 === NULL)

This way you check that $p12_score1 is exactly null.

Upvotes: 0

darkheir
darkheir

Reputation: 8950

Try

if($p12_score1 !== null) {
    $equal[] = $p12_score1;
} else {
echo "null";
}
print_r ($equal);

Upvotes: 0

Bogdan Burym
Bogdan Burym

Reputation: 5512

Try this:

IF(!empty($p12_score1)){
$equal[] = $p12_score1;
}
else {
echo "null";
}
print_r ($equal);

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 131891

However is_null also considers the value 0 a null and won't print it.

No. http://codepad.org/mjiGfhTB

However, you use the comparisong operator

$p12_score1==NULL

and in this case: In loosely typed languaged null is equal to 0 (and some others ;)). However, PHP supports the identity-comparisong

$p12_score1===NULL

A sidenote: !$a == $b is slightly ugly. Use the real "not equal" !=, or !==.

Upvotes: 1

Jon
Jon

Reputation: 437386

is_null does not consider the value 0 equal to null.

Your code uses == for the comparison, which does not make this distinction. Use the identical operator === or is_null instead:

// One way to do it:
if(!$p12_score1 !== NULL)

// Another:
if(!is_null($p12_score1))

Upvotes: 2

Related Questions