Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

foreach

php

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?

like image 931
Himmators Avatar asked Nov 30 '22 09:11

Himmators


1 Answers

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.

like image 135
norwebian Avatar answered Dec 10 '22 14:12

norwebian