Simone Simone - 3 months ago 7
HTML Question

How can I use a foreach loop and set small variations at fixed positions?

I already search for long time on this forum and I can't find a solution to this problem.

I need to create a

foreach
loop for 12 elements but 3 of them have different class.

This is what I have done so far:

$result = $db->query("SELECT `views` FROM `views` WHERE `views` = `id` AND DATE_SUB(CURDATE(),INTERVAL 7 DAY) <= date(`views`.`time`) ORDER BY `id` DESC LIMIT 12");

while($row = $result->fetch_assoc()) {
$users[] = $row;
}

$output .= '<ul>';
foreach($rows as $row) {
$output .= '<li class="grid__item"></li>';
}
$output .= '<ul>';

return $output;


How can I add a different class to
li
objects at 2, 8 and 12 position?

To output something like this:

<ul>
<li class="grid__item"></li>
<li class="grid__item grid__item--deco grid__item--deco-1"></li>
<li class="grid__item"></li>
<li class="grid__item"></li>
<li class="grid__item"></li>
<li class="grid__item"></li>
<li class="grid__item"></li>
<li class="grid__item grid__item--deco grid__item--deco-2"></li>
<li class="grid__item"></li>
<li class="grid__item"></li>
<li class="grid__item"></li>
<li class="grid__item grid__item--deco grid__item--deco-3"></li>
</ul>

Answer

Just use the key of foreach, then set the additional class inside the loop block. Just add an if condition:

$i = 1;
$class_keys = array(2, 8, 12);
$output = '<ul>';
foreach($rows as $key => $row) {
              //  ^ use this
    $default_class = 'grid__item';
    if(in_array($key + 1, $class_keys)) {
        $default_class .= " grid__item--deco grid__item--deco-{$i}";
        $i++;
    }
    $output .= "<li class=\"$default_class\"></li>";

}
$output .= '<ul>';