Hello!
I’m using a foreach loop to add events to a timeline. The timeline has 6 rows. For each event thats added, I increase the row number so that each event sits on a different row. However, when I get to the 6th row, I want to restart the loop so that it starts back at 1 again.
I’m having a bit of trouble thinking through this but maybe its actually quite simple??
Here is my current loop:
<?php $index = 0;
foreach($items as $items): $index++; ?>
<li data-timeline-node="{ start:'<?= $items->fromDate() ?> <?=$items->fromTime() ?>', end:'<?= $items->toDate() ?> <?= $items->toTime() ?>', row:'<?php echo $index ?>' }">
<a href="<?= $items->url() ?>"><?= $items->title() ?></a>
</li>
<?php endforeach ?>
Don’t understand what you are trying to achieve, can you explain further? If you restart the loop every time you get to the 6th row, you will end in an infinite loop…
I would like to restart the loop, but the number of events should stop it becoming infinite. I’ll try to diagram the process I’m looking for below:
foreach event:
- add event to timeline at row 1
- add event to timeline at row 2
…
- add event to timeline at row 6
- add event to timeline at row 1
- add event to timeline at row 2
foreach loop ends when there are no more events to add to the timeline
Does that make any more sense?
Inside the loop you can check if the index has reached 6 and if so, then you can reset it (you need to reset the index and not the loop).
ah yes of course, thank you!
On a side node. It’s not a good idea to use the same variable name for the iterable expression and the value, make it
foreach($items as $item)
1 Like