Himmators Himmators - 1 year ago 79
PHP Question

Foreach, special treatment of every n:th item (odd, even for example)

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?

Answer Source

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:

foreach ($blogusers as $bloguser) {
    if($i % 4 === 0) $extraclass= "fourthClass";
    $resultHTML .= "<div class=\"standardClass $extraclass\">$bloguser</div>";
echo $resultHTML;

Could be made more compact with the ternary operator, but this is the principle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download