Codded
Codded

Reputation: 1256

Php Array chunk: echo something different for first chunk

I am using array_chunk but i want to be able to echo something different for the first array in the chunk. Not sure on how to do this and could not find anything. Any help/guidance would be appreciated.

Say i use:

     foreach (array_chunk($entries, 4) as $row) { 

    if (the array chunk is the first) {echo '<div class="cn_page" style="display:block;">';}
    else {echo '<div class="cn_page">';} 

}

Full code below:

echo '

<div id="cn_preview" class="cn_preview">';

foreach($entries as $entry){
echo '<div class="cn_content" style="top:5px;">
      <img src="newsslider/images/polaroidphotobar.jpg" alt=""/>
      <h1>'.$entry->title.'</h1>
      <span class="cn_date">'.$entry->modified.'</span>
      <span class="cn_category"></span>
      <p>'.$entry->text.'</p>
      <a href="" target="_blank" class="cn_more">Read more</a>
      </div>';     
}
echo '</div>';


echo '<div id="cn_list" class="cn_list">';

foreach (array_chunk($entries, 4) as $row) { 

if (the array chunk is the first) {echo '<div class="cn_page" style="display:block;">';}
else {echo '<div class="cn_page">';}

foreach ($row as $entry) {
$i++;

if ($i == 1){echo '<div class="cn_item selected">';}
else {echo '<div class="cn_item">';}

echo '<h2>'.$entry->title.'</h2>
<p>'.$entry->text.'</p>
</div>';
echo '</div>'; 

}
echo '</div>'; 
}
echo'<div class="cn_nav">
            <a id="cn_prev" class="cn_prev disabled"></a>
            <a id="cn_next" class="cn_next"></a>
</div>
</div>
</div>';

Upvotes: 1

Views: 562

Answers (1)

Jacob Oettinger
Jacob Oettinger

Reputation: 766

That would be:

foreach (array_chunk($entries, 4) as $key => $row) { 
    if ($key == 0) {
        echo '<div class="cn_page" style="display:block;">';
    } else {
        echo '<div class="cn_page">';
    } 
}

Upvotes: 3

Related Questions