Elimate Duplicate Items from a for each

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

I'm creating a tag menu based on the titles of a list page. I am struggling with eliminating duplications of the same event title. It seems this should be easy, but the various codes I find around the forums and internet don't seem to work right for this. I've tried a variety of array_unique situations, but can't seem to get it right. Please advise.

<?php foreach ($events_listRecords as $record): ?>
  <a href="http://abc.com/title=<?php echo htmlencode($record['title']) ?>"><?php echo htmlencode($record['title']) ?></a>
<?php endforeach; ?>

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