Add dynamical class name to divs inside a foreach

I am trying the add a different class name to the divs inside the foreach.
This is my code:

$items = $page->collab()->toStructure();
$count = 0;
foreach ($items as $item): ?>
<?php $class= ($count%2 == 0)?"right":""; ?>
<div class=" '$class' ">
    <?php foreach ($item->image()->toFiles() as $image): ?>
    <img src="<?= $image->crop(400)->url() ?>">
    <?php endforeach ?>
    <h3><?= $item->name()->html() ?></h3>
    <p><?= $item->projects() ?></p>
<?php endforeach ?>

Any ideas of what am I doing wrong?


2 issues:

  • your are not echoing your $class variable: <div class="<?= $class ?>">
  • you are missing to increase your counter variable in the loop

But in fact, adding a class is not really necessary to style these items as you can do that with CSS only, using the nth-child() selector with even and odd.

oh, that’s right! was over thinking…
nth-child() works perfectly, many thanks @texnixe