In the code below I want to apply the object “$activeclass” as a DIV class. I thought the end pointer I included would apply this only to the last iteration of the array, but instead it is applying the class to all iterations.
<div id="right_bottom">
<?
$content = is_array($pagedata->content) ? $pagedata->content : array($pagedata->content);
foreach($content as $item){
$activeclass = end($content) ? 'active' : ' ';
?>
<div id="right_side">
<div id="<?=$item->id?>" class="side_items <?=$activeclass?>">
<a class="content" href="<?=$item->id?>"><img src="<?=PROTOCOL?>//<?=DOMAIN?>/img/content/<?=$item->image?>"><br />
<strong><?=$item->title?></strong></a><br />
<h2><?=date('F j, Y', strtotime($item->published))?></h2><br />
</div>
</div>
<?
}
?>
</div>
Any ideas where I am making a mistake? How can I apply the class $activeclass only to the last iteration of my “foreach” statement?
The simplest way is to keep a count:
Alternatively, you can compare the last element with the current element (if your array is consecutively numerically indexed starting with 0 [Thanks to webbiedave for pointing out the assumptions made by this method]):
Note that this approach will not work if your array has duplicate items.
Finally, you can compare indexes in the following way: