1

I have a custom component that displays "coming soon" items based on dates. I am trying to hide all those items that are past today's date. However if there is no future items it does not display the custom text.

How do I do it inside a foreach loop? Or how can I insert php break? Or is there a better way of doing this?

<?php foreach ($this->items as $item) : ?>
    <?php if($item->state ==1 && strtotime($item->event_date) > strtotime(JFactory::getDate())): ?>
        <div class="cont">
            <!-- Display values from DB -->
        </div>
    <?php elseif($item->state ==1 && strtotime($item->event_date) < strtotime(JFactory::getDate())): ?>
        <!-- Dont display anything -->
    <?php else: ?>
        <div class="cont">
            <!-- Display custom text -->
        </div>
    <?php endif; ?>
<?php endforeach; ?>
3

You need to handle the "else" section outside of the foreach loop, since if there are no items, the foreach loop never runs:

<?php $item_displayed = false; ?>
<?php foreach ($this->items as $item) : ?>
    <?php if($item->state ==1 && strtotime($item->event_date) > strtotime(JFactory::getDate())): ?>
        <?php $item_displayed = true; ?>
        <div class="cont">
            <!-- Display values from DB -->
        </div>
    <?php endif; ?>
<?php endforeach; ?>
<?php if (!$item_displayed) : ?>
    <div class="cont">
        <!-- Display custom text -->
    </div>
<?php endif; ?>

Basically, I added a variable that states that an item has not been displayed. If any item in the loop is displayed, I then switch that variable to true. After the loop I will then display the custom text if there was no items or if no item is upcoming.

  • Thank you very much for the solution and also the explanation. It worked like a charm! – Kannan Naidu May 8 '14 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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