Michael Falciglia
Michael Falciglia

Reputation: 1046

PHP add <div "style="clear"> </div> in a loop after every 4 records

To style a page correctly I need to add <div style="clear:both"></div> after every 4 records in a loop.

Currently every records outputted into a php file and displayed in a <div> like I have below.

<div>content</div> 

On every 4th record I would like to add a clear <div> like this:

<div>content</div>
<div style="clear:both"></div>

Upvotes: 1

Views: 4039

Answers (3)

sjagr
sjagr

Reputation: 16502

Use a modulos

$i = 1;
while ($row = mysql_fetch_array($result) {
    echo '<div>'.$row.'</div>';
    if (($i++ % 4) == 0) echo '<div style="clear:both;"></div>';
}

You should not use mysql as it is deprecated. Instead, use MySQLi or PDO.

Upvotes: 10

andreas
andreas

Reputation: 8004

I suggest you to use CSS as well, for example like this:

CSS

<style type="text/css">
    .normaldiv {
        /* other stuff here */
    }
    .cleardiv {
        clear: both;
    }
</style>

PHP

$array = array(
    'data1',
    'data2',
    'data3',
    ...
    'datan'
);

$html = '';

foreach ($array as $i => $data) {
    // Add class "normaldiv" or "normaldiv cleardiv"
    $html .= '<div class="normaldiv' . ( $i%4 == 3 ? ' cleardiv' : '' ) . '">' . $data . '</div>';
}

// Do anything with your html string
echo $html;

Maybe you need to adjust it to your needs (for example using an if clause within the foreach, if you want to make an empty div without css class "normaldiv").

Upvotes: 1

Hugo Tunius
Hugo Tunius

Reputation: 2879

Adding this to you loop body ought to do the trick

if ($i != 0 && $i % 4 == 0) 
  //Output clear div here

Upvotes: 2

Related Questions