Thursday, 30 August 2018

PHP - The counter in the foreach loop does not work

I have a foreach loop that I need numbered classes so I set up a counter:

 <?php
 $counter = 0;
  ?>
  <?php
$html = '';
foreach ($json['feed']['entries'] as $entries){
$counter++;
$html .= '<a href="' .$entries['link']. '"><span class="feeddisplay_title">'.$entries['title']. ' </span></a>';
    if($entries['publishedDate'] != '') {
        $html .='<span class="feeddisplay_date">' .$entries['publishedDate'].    '</span>';
    }
    $html .= '<p>' .$entries['contentSnippet']. '</p>';
}
?>
<div class="box feed-<?php echo $counter; ?>">
 <div class="box-heading"><?php echo $heading_title; ?>:</div>
 <div class="box-content">
<div class="feeddisplay"><?php echo $html ?></div>
 </div>
 </div>

And my output class is "feed-1" over and over. It doesn't go up. I've tried a few variations and I'm stuck.

It's because you're echoing the counter variable outside of the foreach loop.
By the time $counter is called, the value of counter has been added up through the foreach loop, so you're just displaying the final count.

0 comments:

Post a Comment