Matt Elhotiby
Matt Elhotiby

Reputation: 44066

Is there an easy way to do 4 at a time in a php foreach loop

I have this php foreach loop

<?php $all_news = $this->db->query("Select * from news"); ?>
<div class="inner">             
foreach($all_news as $key=>$news){?>
  <div class="news <?php echo ($key%2==1)? 'odd': 'even'?>">
  <div class="news_img">....<?php echo $news['title'] ?>

But the problem is the $all_news may have 20 results or so but the design only allows me to put for 4 news blocks in each inner div...is there a way make this happen so i have only 4 news divs in each inner div

Upvotes: 1

Views: 134

Answers (4)

GolezTrol
GolezTrol

Reputation: 116110

Change your query to only return 4 rows:

SELECT * FROM news LIMIT 4

Alternatively you can change your for-loop.

for($i = 0; $i < min(4, count($all_news)); $i++)
{?>
  <div class="news <?php echo ($i%2==1)? 'odd': 'even'?>">
  <div class="news_img">....<?php echo $all_news[$i]['title'];

<?}

[edit]

See what you mean now. Create two loops:

<?
$index = 0;
while ($index < count($all_news))
{
  $news = $all_news[$index];

  ?>Start outer div<?

  for ($item = 0; $item < 5; $item++)
  {
    ?>Inner div with news item <? echo $news['title'];
  }

  ?>End outer div<?
  $index++;
}

Upvotes: 4

sdleihssirhc
sdleihssirhc

Reputation: 42496

The laziest way would be to just check whether or not you've already done four in the current div on the fly. If you have, close the current div and start a new one:

<div class="inner">
<?php
foreach ($all_news as $key => $news) {
    if ($key % 2) {
        $oddEven = 'odd';
    } else {
        $oddEven = 'even';
        if ($key && $key % 4 === 0) {
            echo '</div><div class="inner">';
        }
    }

    echo "<div class=\"news $oddEven\">";
    // ...
}
?>
</div>

Note that this assumes $all_news has an element at 0, so it makes sure that it doesn't close the first, empty div.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816364

You could use two for loops:

<?php $all_news = $this->db->query("Select * from news"); ?>
<?php for($i = 0, $l = count($all_news); $i < $l; $i+=4): ?>
    <div class="inner">
    <?php for($j = $i; $j < $i+4; $j++): ?>
        <div class="news <?php echo ($j%2==1)? 'odd': 'even'?>">
        <div class="news_img">....<?php echo $all_news[$j]['title'] ?>
    <?php endfor;?>
    </div>
<?php endfor;?>

Another option would be array_chunk [docs].

Upvotes: 1

Paul
Paul

Reputation: 141839

<?php 

$all_news = $this->db->query("Select * from news"); 

echo '<div class="inner">';

$c = count($all_news);
for($i = 0; $i < $c; $i++){
    <div class="news <?php echo ($i%2==1)? 'odd': 'even'?>">
    <div class="news_img">....<?php echo $news['title'] ?>
    if($i % 4 == 3)
        echo '</div><div class="inner">';
}

echo '</div>';

?>

Upvotes: 6

Related Questions