Francesco Francesco - 1 month ago 6
PHP Question

Print field only if value is not empty

I have a foreach statement that prints the label and values of some fields:

<?php
foreach ($this->item->dpfields as $field) {
echo '<li><b>'.$field->label.'</b>: '.$field->value.'</li>';
}
?>


I would like to print only the fields (labels and values) that are not empty.

How should I edit this code?

Answer
<?php 
    foreach ($this->item->dpfields as $field) {
        if (!empty($field->label) && !empty($field->value)) {
             echo '<li><b>'.$field->label.'</b>: '.$field->value.'</li>';
        }
    }
?>
Comments