Saturday, January 21, 2017

Php - Adding divs to a foreach loop every 4 times

Basically what i need to do is wrap a div around the output of the data every 4 loops.

I have the following loop:

foreach( $users_kicks as $kicks ) {
    echo $kicks->brand;
}

For every 4 times it echos that out i want to wrap it in a  so at the end it will look like so:

<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>
<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>
<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>


Solution:
=========
$count = 1;

foreach( $users_kicks as $kicks )
{
    if ($count%4 == 1)
    { 
         echo "<div>";
    }
    echo $kicks->brand;
    if ($count%4 == 0)
    {
        echo "</div>";
    }
    $count++;
}
if ($count%4 != 1) echo "</div>";

//This is to ensure there is no open div if the number of elements in user_kicks is not a multiple of 4



Cheers and thanks !!! For get more refer this link

No comments:

Post a Comment