JeremyC
JeremyC

Reputation: 17

SQL field value of 0 returns empty

I have variable types of data in my SQL database, and I am poplulating a table with PHP.

Sometimes I have 3 columns, sometimes I have more, depending on the type of data. If I use:

    $fourthcolumn=$row['fourth'];
    if(empty($fourthcolumn)){
    // DO NOTHING
    }else{
    echo "<td class='fourth'>" . $fourthcolumn. "</td>";
    }

Then it works as expected with one exception: Some columns are quantities. When the quantity is '0', it is returning as empty and does not make the td with a value of '0'.

In my structure, if there is no info, then the cell is completely blank, and that is what i would expect to come back as empty

Is there any way to return the '0'? What am I doing wrong?

Upvotes: 1

Views: 97

Answers (4)

andrew
andrew

Reputation: 9583

empty(0) evaluates to true in php

see manual

so you could check explicitly

if(empty($fourthcolumn) && $fourthcolumn !==0 && $fourthcolumn !== "0"){
// DO NOTHING
}else{
echo "<td class='fourth'>" . $fourthcolumn. "</td>";
}

Upvotes: 3

John Wesley Gordon
John Wesley Gordon

Reputation: 910

The php document for empty() defines how it functions as "Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE."

http://php.net/manual/en/function.empty.php

0 would be considered false.

I would suggest using instead

$fourthcolumn=$row['fourth'];
if(isset($fourthcolumn)){
    echo "<td class='fourth'>" . $fourthcolumn. "</td>";
}else{
    // DO NOTHING
}

isset checks if a variable is not null.

http://php.net/manual/en/function.isset.php

Upvotes: 1

Khrisna Gunanasurya
Khrisna Gunanasurya

Reputation: 745

Use this one

$fourthcolumn=$row['fourth'] ?: 0;

It describe like this

if $row['fourth'] is null then 0

Upvotes: 0

dave
dave

Reputation: 64677

bool empty ( mixed $var )

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

In PHP, 0 == false. So empty (correctly) returns true if the value it is checking is 0.

The problem could be solved as follows:

if(empty($fourthcolumn) && $fourthcolumn !== 0 && $fourthcolumn !== "0"){
// DO NOTHING
}else{

Where you check to make sure the $fourthcolumn is not equal to the number 0 or the string "0" (using strict equality, so it won't match for false, or an empty string, for example).

Upvotes: 0

Related Questions