0

I've got a form where some fields are optional. I later display these fields.

I'm trying to show a value from my database only if there is a value. Otherwise, show nothing.

Here is what needs to be displayed if there is a value -

<div class='category' style='font-size:20px; background-color:f2f2f2'>".$row['project_category']."</div>

Should I use an 'if (strlen($prjcat) > 0)'?

Thanks!

2

4 Answers 4

1

You are looking for an if statement to check if the value is empty:

if(!empty($row['project_category'])){
    echo "<div class='category' style='font-size:20px; background-color:f2f2f2'>".$row['project_category']."</div>";
}
0

PHP has just the function you're looking for ~ empty()...

<?php if (!empty($row['project_category'])) : ?>
<div class="category" style="font-size:20px; background-color:f2f2f2;">
    <?= htmlspecialchars($row['project_category']) ?>
</div>
<?php endif ?>

or, if you're looping over some field names

<?php foreach ($fields as $field) : ?>
    <?php if (!empty($row[$field])) : ?>
    <div class="category" style="font-size:20px; background-color:f2f2f2;">
        <?= htmlspecialchars($row[$field]) ?>
    </div>
    <?php endif ?>
<?php endforeach ?>
0

it is better to use this

<?php if(trim($row['project_category']) != "") { ?>
     <div class="category" style="font-size:20px; background-color:f2f2f2"> <?php echo $row['project_category']; ?></div>
<?php } ?>

Do not use empty if your column value can have zero. Because when you use empty($row['project_category']) and $row['project_category'] = 0 it will return true. For more info check here

-1

You can try out not empty for this:

if(!empty($row['project_category'])){
    echo '<div class="category" style="font-size:20px; background-color:f2f2f2">'.$row['project_category'].'</div>';
}
2
  • I don't think that it is a good idea to use ' for quoting the whole string. And the missing echo was a typo?
    – Tom
    Oct 9, 2014 at 5:25
  • Correct Tom. However it is slightly faster to use single quotes. PHP won't use additional processing to interpret what is inside the single quote.when you use double quotes PHP has to parse to check if there is any variables in there. Oct 9, 2014 at 6:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.