Jacob
Jacob

Reputation: 2071

Foreach, add class to each three

Im having some PHP problems. I have a array that I display with foreach The code looks like this:

foreach($names as $key => $name):

echo $name;

endforeach;

Lets say there are 6 names, then it would output this:

Name1
Name2
Name3
Name4
Name5
Name6

Now the thing I need is to group three names in a div. Like this

<div class="group">
Name1
Name2
Name3
</div>
<div class="group">
Name4
Name5
Name6
</div>

But I actually have no idea how to do this, I've tried a few things that didn't work.

What is the best way to structure this?

Thanks in advance! Let me know if there was something unclear that I need to explain better.

Upvotes: 0

Views: 145

Answers (3)

oshell
oshell

Reputation: 9123

This would be my solution:

$names=array("peter", "tom", "felix", "patrick", "paul", "sam", "bill");

foreach($names as $key => $name){
    //if the key is 0 we just started and have to open a div
    if($key==0){
        echo '<div class="group">';
    }

    //actually echo the name in our div
    echo $name;

    //if the key can be divided by 3 we have to close our div
    //we add one because index starts with 0
    $close=is_int(($key+1)/3);

    //and we want to close the div if there is no more element in our array
    if(!array_key_exists($key+1, $names)){
       $close=true;
    }


    if($close){
        //close the div 
        echo '</div>';
        //if there is another element in our array we have to open the tags again
        if(array_key_exists($key+1, $names)){
            echo '<div class="group">';
        }
    }
}

Upvotes: 1

Unix von Bash
Unix von Bash

Reputation: 730

echo '<div class="group">'
$index = 0;

foreach($names as $key => $name):

echo $name;
$index++;
if($index%3==0)
{
echo '</div>'
echo '<div class="group">'
}
endforeach;
echo '</div>'

Upvotes: 0

Chitowns24
Chitowns24

Reputation: 960

$count = 1;
foreach($names as $key => $name):
if$count == 1)
{
echo '<div class="group">';
}

echo $name;
$count++;
if($count == 3)
{
echo '</div>';
$count = 1;

}

endforeach;

I hate counting in a foreach but it seems like the easiest solution, maybe a for loop where it is already being counted would be better suited.

Upvotes: 1

Related Questions