1
<ul>
    <?php foreach (array_slice($items, 0, 3) as $item): ?>
        <?php if (!isset($item->story)): ?> <!-- hide story updates -->
          <li>
            <?php if (isset($item->message)) echo $item->message; ?>
          </li>
        <?php endif; ?>
    <?php endforeach; ?>
</ul>

I am displaying a news feed, and only want to display the items without a story update. So i am using !isset to check if a story item is present, and hide the item if it is.

This works perfectly, but now I am trying to display 3 results in the feed, but i think the story items are still being counted in the foreach, so when the last 3 updates are story items, nothing displays in the feed.

I have read this question which looks like what I am trying to do, but I dont understand where he has got the $elementkey variable from, and what it does?

How do I remove the item from the foreach, and remove its count so 3 items will display?

Community
  • 1
  • 1
Collins
  • 1,069
  • 14
  • 35
  • 1
    Please show us your code where you try to implement the limit of 3 posts – Rizier123 Feb 06 '15 at 18:51
  • Its controlled in a function in a drupal .module file, but the same can be done using array_slice that i have just added to the question – Collins Feb 06 '15 at 18:55
  • and.. why would you think they wouldn't be counted?.. – Brett Caswell Feb 06 '15 at 18:55
  • It shows 3 results when the last 3 items didnt have stories, but when a story is in the foreach, only 2 items display, or no items display – Collins Feb 06 '15 at 18:56
  • @Collins, of course.. that's the expected behavior.. you're not conditionally slicing the `$items` array.. so you're looping through three items.. which may or may not contain story – Brett Caswell Feb 06 '15 at 18:58

1 Answers1

2

This should work for you:

(Here i just added a $count variable which i only increment if a message get's posted. And after 3 i break the foreach)

<ul>
<?php $count = 0;
        foreach ($items as $item): ?>
    <?php if ($count >= 3) break; if (!isset($item->story)): ?> <!-- hide story updates -->
      <li>
        <?php if (isset($item->message)) {
                echo $item->message;
                $count++;
              }
        ?>
      </li>
    <?php endif; ?>
<?php endforeach; ?>
</ul>
Rizier123
  • 58,877
  • 16
  • 101
  • 156