First and Last Class on a list
This function appears in the Codit Module
Here is a function that allows you to quickly get back a class as 'first', 'middle', 'last' and in a case of a single item list 'first last'
<?php
/**
* Accepts counts info from within a foreach loop and returns a class string
*
* @param int $i_current_count
* The count of the current loop index. First loop should start at 1
* @param int $i_max_count
* The maximum number of loops (the count of the items in the array)
*
* @return string
* 'first' if it is the first loop,
* 'middle' if it is the middle loops,
* 'last' if it is the last loop, 'first last' if there is only one item
*/
function codit_first_last_class($i_current_count = 0, $i_max_count = 0) {
$s_first_last_class = '';
$s_first_last_class .= ($i_current_count == 1) ? 'first': '';
$s_first_last_class .= (($i_current_count > 1) && ($i_current_count < $i_max_count)) ? 'middle': '';
$s_first_last_class .= ($i_current_count == $i_max_count) ? ' last': '';
return $s_first_last_class;
}
?>
In use it looks like this
<?php
// start a counter for checking placing first and last
$iIndexCounter = 0;
$iMaxCount = count($aSomeArray);
foreach($aSomeArray as $item){
//check first or last
$sFirstLastClass = c0dit_first_last_class(++$iIndexCounter , $iMaxCount );
...
$sOutput .= "<div class='amenity_group $sFirstLastClass'>\n";
...
?>