ForEach loop: Output something different on every second result

Posted by Wade D Ouellet on Stack Overflow See other posts from Stack Overflow or by Wade D Ouellet
Published on 2010-05-24T22:50:20Z Indexed on 2010/05/24 23:01 UTC
Read the original article Hit count: 452

Filed under:
|
|
|
|

I have two for each loops and I am trying to output something different for each second result:

foreach ($wppost as $wp) {
            $wp_title = $wp->post_title;
            $wp_date = strtotime($wp->post_date);
            $wp_slug = $wp->post_name;
            $wp_id = $wp->ID;
            // Start Permalink Template
            $wp_showurl = $wp_url;
            $wp_showurl = str_replace("%year%", date('Y', $wp_date), $wp_showurl);
            $wp_showurl = str_replace("%monthnum%", date('m', $wp_date), $wp_showurl);
            $wp_showurl = str_replace("%day%", date('d', $wp_date), $wp_showurl);
            $wp_showurl = str_replace("%hour%", date('H', $wp_date), $wp_showurl);
            $wp_showurl = str_replace("%minute%", date('i', $wp_date), $wp_showurl);
            $wp_showurl = str_replace("%second%", date('s', $wp_date), $wp_showurl);
            $wp_showurl = str_replace("%postname%", $wp_slug, $wp_showurl);
            $wp_showurl = str_replace("%post_id%", $wp_id, $wp_showurl);
            // Stop Permalink Template
            $wp_posturl = $blog_address . $wp_showurl;
            echo '<li><a href="'.$wp_posturl.'" title="'.$wp_title.'">'.$wp_title.'</a></li>';          
        }

For this one I want it to echo li class="even" instead of just li for each second result. I think this will have to be changed to a for loop to accomplished this but I am not sure how that is done without breaking it.

Exact same for this one:

if(is_array($commenters)) {
       foreach ($commenters as $k) {
         ?><li><?php
          if($ns_options["make_links"] == 1) {
            $url = ns_get_user_url($k->poster_id);
            if(trim($url) != '')
            {
                echo "<a href='" . $url . "'>";
            }
          }
          if($ns_options["make_links"] == 2) {
            $url = ns_get_user_profile($k->poster_id);
            echo "<a href='" . $url . "'>";
          }


          $name = $bbdb->get_var("
       SELECT user_login 
       FROM $bbdb->users
       WHERE ID = $k->poster_id");
         echo ns_substr_ellipse($name, $ns_options["name_limit"]);

          if(trim($url) != '' && $ns_options["make_links"] == 1) {
             echo "</a>";
          }
          if($ns_options["make_links"] == 2) {
            echo "</a>";
          }
          if ($ns_options["show_posts"] == 1)
          {
          echo " (" . $k->num_posts . ")\n";
          }
          echo $ns_options["end_html"] . "\n";
          unset($url);
       }
    } else {
      ?></li><?php
    }

Thanks,

Wade

© Stack Overflow or respective owner

Related posts about php

Related posts about loops