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
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.

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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
   }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.