detecting first record listed in any sort

5 posts by 4 authors in: Forums > CMS Builder
Last Post: October 11, 2009   (RSS)

Re: [rez] detecting first record listed in any sort

By irelocation - October 9, 2009

I have the same issue, Rez. Anyone have any ideas? I am especially interested in doing it for ascending order....
home security system

Re: [rez] detecting first record listed in any sort

By Damon - October 10, 2009

Here is one way of treating the first item in your list a different way no matter how the list is sorted.

<ul>
<?php $counter = 1; ?>
<?php foreach ($inventoryRecords as $record): ?>
<?php if($counter == 1) : ?>
<li class="first-item"><?php echo $record['name'] ?></strong></li>
<?php else : ?>
<li><?php echo $record['name'] ?></li>
<?php endif; ?>
<?php $counter++ ?>
<?php endforeach; ?>
</ul>


You set a $counter to one before the foreach loop. Then in the loop, you check with an if statement if the $counter equals 1. If it does, this is the first record, and style it differently, else style it another way.

The $counter than increases after the first loop so the $counter won't equal 1 again.

I'm sure there is lots of ways to get the same results but this is the way I usually do it. :)

Hope this makes sense and helps.
Cheers,
Damon Edis - interactivetools.com

Hire me! Save time by getting our experts to help with your project.
http://www.interactivetools.com/consulting/

Re: [Damon] detecting first record listed in any sort

By rez - October 11, 2009 - edited: October 11, 2009

Ah ha. Brilliant. You can treat any number.

While we are on the subject, how would you find the last one in a consistent way?

:)

Re: [rez] detecting first record listed in any sort

By Chris - October 11, 2009

Hi rez,

Here you go:

<ul>
<?php $counter = 1; ?>
<?php foreach ($inventoryRecords as $record): ?>
<?php if ($counter == 1): ?>
<li class="first-item"><?php echo $record['name'] ?></strong></li>
<?php elseif ($counter == sizeof($inventoryRecords)): ?>
<li class="last-item"><?php echo $record['name'] ?></strong></li>
<?php else: ?>
<li><?php echo $record['name'] ?></li>
<?php endif; ?>
<?php $counter++ ?>
<?php endforeach; ?>
</ul>


I hope this helps. Please let me know if you have any questions.
All the best,
Chris