Sajal
Sajal

Reputation: 305

Creating row using php loop

I want to create a row if columns greater than 3 using PHP loop because i am using wordpress

My code is here

<div class="row">
    <div class="column">column1</div>
    <div class="column">column2</div>
    <div class="column">column3</div>
</div>

If columns are greater than 3, then it should create a new row like this

<div class="row">
    <div class="column">column1</div>
    <div class="column">column2</div>
    <div class="column">column3</div>
</div>

<div class="row">
    <div class="column">column1</div>
  </div>

Any help will be highly appreciated.

Thanks in advance

Upvotes: 0

Views: 2237

Answers (3)

h2ooooooo
h2ooooooo

Reputation: 39542

Sure - just use modulus:

<?php
    $elements = array('foo', 'bar', 'rab', 'oof');

    echo '<div class="row">';
    foreach ($elements as $i => $element) {
        if ($i > 0 && $i % 3 == 0) {
            echo '</div><div class="row">';
        }
        echo '<div class="column">' . $element . '</div>';
    }
    echo '</div>';
?>

DEMO

Output:

<div class="row">
    <div class="column">foo</div>
    <div class="column">bar</div>
    <div class="column">rab</div>
</div>
<div class="row">
    <div class="column">oof</div>
</div>

Upvotes: 4

Durul Dalkanat
Durul Dalkanat

Reputation: 7435

There is alternative solution with function.

<?php
// Managing the Code -- Functions: Handling a Variable Number of Parameters
// building a row of 10 <td> columns with a variable number of items
function preferencesRow()
{
    // initialize $output
    $output = '';
    // use "func_get_args()" to collect all parameters into an array
    $params = func_get_args();
    // used to make sure 10 columns are filled
    $maxCols = 10;

    // loop through the parameters
    foreach ($params as $item) {
        $output .= "<td width='80px' align='center'>$item</td>\n";
        $maxCols--;
    }

    // fill in the rest of the row with empty columns
    for ($x = 0; $x < $maxCols; $x++) {
        $output .= "<td width='80px'>&nbsp;</td>\n";
    }
    return $output;
}

// NOTE: you can use "." or "," with echo
echo '<h1>Preferences</h1><hr />' . PHP_EOL;    
echo '<table border=1>' . PHP_EOL;
echo '<tr><th>Tarzan</th>';
echo preferencesRow('Africa', 'jungles', 'tantor', 'mangani', 'cabin in the woods', 
                    'hunting', 'swinging in trees', 'Jane');
echo '</tr>';
echo '<tr><th>Jane</th>';
echo preferencesRow('London', 'parties', 'dancing', 'social events', 'lavish estates');
echo '</tr>';
echo '</table>' . PHP_EOL;

Upvotes: 0

Adam
Adam

Reputation: 1371

You need something like this:

<?
echo '<div class="row">';
for ($i=0; $i<15;$i++){
    if ($i%3 == 0 && $i != 0){
        echo '</div><div class="row">';
    }
    echo '<div class="column">column '.($i+1).'</div>';

}
echo '</div>';
?>

WORKING CODE

Upvotes: 1

Related Questions