Reputation: 17
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
Reputation: 9583
empty(0)
evaluates to true in php
so you could check explicitly
if(empty($fourthcolumn) && $fourthcolumn !==0 && $fourthcolumn !== "0"){
// DO NOTHING
}else{
echo "<td class='fourth'>" . $fourthcolumn. "</td>";
}
Upvotes: 3
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
Reputation: 745
Use this one
$fourthcolumn=$row['fourth'] ?: 0;
It describe like this
if $row['fourth']
is null then 0
Upvotes: 0
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