Reputation: 1487
Okay so I have this small database containing columns named "tag1", "tag2", "tag3" and "tag4". Now, I display those tags along with the corresponding portfolio item, but not every portfolio item has 4 tags, meaning sometimes some of these tag fields can be empty.
Now I'm printing all my portfolio items in an if loop, so for every item I print all the 4 tags meaning that if some tag fields are empty, I also receive empty spaces (e.g. in my list the bullets show up but obivously no text).
So basically what I want to do, is ONLY print the tag if it is not empty. But I don't understand how to do this with multiple tags?
This is my code:
print("
<ul class=\"tagList\">
<li>{$row['tag1']}</li>
<li>{$row['tag2']}</li>
<li>{$row['tag3']}</li>
<li>{$row['tag4']}</li>
</ul>
");
Upvotes: 0
Views: 247
Reputation: 3
You could use array_filter($row,'strlen'); to remove all empty elements and then loop through $row printing each tag.
However, I would guess that $row contains more then just tag1, tag2, tag3, and tag4. So you could try this instead.
print "<ul class=\"tagList\">";
for($i=1;$i<5;$i++) {
if(strlen($row['tag'.$i])>0) {
print "<li>{$row['tag'.$i]}</li>";
}
}
print "</ul>";
Upvotes: 0
Reputation: 46300
You should check if the variable is empty before printing it:
print("<ul class=\"tagList\">");
if($row['tag1']) {
print("<li>{$row['tag1']}</li>");
}
if($row['tag2']) {
print("<li>{$row['tag2']}</li>");
}
etc.
You can make it easier for yourself by using a for loop:
for($i = 1; $i < 5; $i++) {
if($row['tag'.$i]) {
print("<li>{$row['tag'.$i]}</li>");
}
}
Upvotes: 3
Reputation: 2693
This will dump the whole of $row. IF this is what you want.
$row=array_filter($row); // see below
if(sizeof($row)>0)
{
echo '<ul><li>'.implode('</li><li>', $row).'</li></ul>';
}
NOTE: array_filter will remove elements with the values: false, null and 0
Upvotes: 0
Reputation:
You can use PHP's empty comparison to check if the value is empty. If it's not empty, print the value, otherwise, print nothing.
For something this small, you could even encapsulate your <li>
elements in the empty comparison.
Upvotes: 0