Timothy Fisher Timothy Fisher - 4 years ago 106
PHP Question

How to split an array into groups of 3 and then style every other row differently?

If I have an array like this:

$food = array('steak', 'chicken', 'vegetables', etc);


How can I loop through the array and display each of the items in a list of 3, and also style every other row differently?

Like:

Steak chicken vegetables
Stuff stuff stuff // style this one differently
Blah blah blah
Stuff stuff stuff // style differently


I know I can do:

foreach (array_chunk($food, 3, true) as $array) {
echo '<ul>';
foreach ($array as $item) {
echo '<li>'.$item.'</li>';
}
echo '</ul>';
}


Just not sure how to get the every other row thing in addition to that.

Answer Source

Using your foreach() loop, add the key to the as key => value. Then you can use modulo % to modify every other row.

foreach (array_chunk($food, 3, true) as $key => $array) {
    $oddeven = ($key%2 == 1) ? ' class="even"' : '';
    echo '<ul'.$oddeven.'>';
    foreach ($array as $item) {
        echo '<li>'.$item.'</li>';
    }
    echo '</ul>';
}

example - https://3v4l.org/LdSgJ

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download