Jump to content

Add class at end of For each


unemployment

Recommended Posts

I need to add a class to the div at the end of my for each.  How do I say if the function breaks, add in class="lastmessage"

 

<?php

$counter = 0;

foreach ($conversations as $conversation)
{
	if(++$counter == 5) break;

	?>
	<div class="(add class here)">
		<a href="blah"><?php echo blah; ?></a>					
	</div>
                <?php
         }
?>

Link to comment
https://forums.phpfreaks.com/topic/227908-add-class-at-end-of-for-each/
Share on other sites

I need to add a class to the div at the end of my for each.  How do I say if the function breaks, add in class="lastmessage"

 

<?php

$counter = 0;

foreach ($conversations as $conversation)
{
	if(++$counter == 5) break;

	?>
	<div class="(add class here)">
		<a href="blah"><?php echo blah; ?></a>					
	</div>
                <?php
         }
?>

 

Edit:  I don't just want to say to add it at the end of the foreach in the event that their are less than 5 messages.

That logic seems a bit funky. What are you trying to achieve? Will there only ever be 5 elements in the array? A better explanation would help.

 

I have a list of messages in sidebar.  The most that will display is 5 of them.  I want to set a border-bottom to the last element in the foreach loop.  Sometimes you may have less than 5 messages.  If your inbox only has 3, 3 will be displayed.  Does that help?

Just use a normal for-loop:

 

$numConversations = count($conversations);

for($i = 0; $i < $numConversations; ++$i)
{
   if(($i + 1) == $numConversations) // adding 1 to the index because arrays are ZERO-indexed, so $conversations[0] is your first one
   {
      // add your CSS class
   }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.