Foreach, special treatment of every n:th item (odd, even for example)
foreach, php
Solution
Use the modulus operator. I see @Alex has beaten me to the mark with this, but I offer this code I wrote and tested, so that others can see more clearly the principle:
$blogusers=array('a','b','c','d','e','f','g','h','i','j');
$i=0;
foreach ($blogusers as $bloguser) {
if($i % 4 === 0) $extraclass= "fourthClass";
$resultHTML .= "<div class=\"standardClass $extraclass\">$bloguser</div>";
$i++;
$extraclass="";
}
echo $resultHTML;
Could be made more compact with the ternary operator, but this is the principle.
Problem
I have a foreach that looks like this: ``` foreach ($blogusers as $bloguser) { $args = array( 'author' => $bloguser->user_id, 'showposts' => 1, 'caller_get_posts' => 1 ); $my_query = new WP_Query($args); if( $my_query->have_posts() ) { $user = get_userdata($bloguser->user_id); userphoto($bloguser->user_id, "<div class='all_authors'><a href='http://blogg.nacka.se/nastasteg/author/".$user->user_login . "'>","</a><ul><li><a href='http://blogg.nacka.se/nastasteg/author/".$user->user_login . "'>" .$user->user_firstname."</a></li><li class='occupation'>".$user->user_lastname."</li></ul></div>", array('width' => 135, 'height' => 135)); #echo "<div class='all_authors'><a href='http://blogg.nacka.se/nastasteg/author/".$user->user_login . "'><img src='http://www.gravatar.com/avatar/" . md5( strtolower( trim( " $user->user_email " ) ) )."?s=135' /></a><ul><li><a href='http://blogg.nacka.se/nastasteg/author/".$user->user_login . "'>" .$user->user_firstname."</a></li><li class='occupation'>".$user->user_lastname."</li></ul></div>"; } } ``` In every foth div, Would like to add an extra class. How do I do this?