Elimate Duplicate Items from a for each

3 posts by 2 authors in: Forums > CMS Builder
Last Post: May 17, 2014   (RSS)

By gregThomas - May 16, 2014

Hi Josh,

It sounds like you need a way to check what values have already been listed, and ensure that duplicate values are not displayed again. This method should work:

<?php $alreadyListed = array();  ?>
<?php foreach ($events_listRecords as $record): ?>
  <?php if(!in_array(strtolower($record['title']), $alreadyListed)): ?>
    <a href="http://abc.com/title=<?php echo htmlencode($record['title']) ?>"><?php echo htmlencode($record['title']) ?></a>
    <?php $alreadyListed[] = strtolower($record['title']); ?>
  <?php endif; ?>
<?php endforeach; ?>

So the $alreadyListed array is created to store titles that have been displayed. When a title is displayed we add its name to the $alreadyListed array. Then an if statement is used to check if a title had already been displayed by looking in the areadyListed array. If it has been displayed already, the item will be skipped. 

The strtolower function will ensure that items of a different case will not be displayed twice (eg dog, DoG). But otherwise the titles must match exactly to be skipped.

Thanks!

Greg

Greg Thomas







PHP Programmer - interactivetools.com

Perfect! Thank you so very much. And thank you for the explanation of why it works also.

Josh