Repeat pages in pages collection

Is it possible to repeat pages in a pages collection?

What I want to do is:

- obtain $somePages collection
- if $somePages->count < 5
  - build the collection $repeatedPages which contains $somePages repeated a number of times until $repeatedPages is >= 5
  - if $repeatedPages > 5
    - $repeatedPages = $repeatedPages->limit(5)

For example:

if
$somePages = page1, page2
then
$repeatedPAges = page 1, page 2, page 1, page2, page 1

Thank you

That’s not possible, because if you add a page to a collection that already contains that element, it will be ignored. Could you explain your use case for repeating pages?

What you could do is loop through the same collection multiple times depending on number of elements in your collection.

That answers my question, thank you @texnixe

Atm I am doing this by repeating the foreach loop as many times as needed to achieve a certain number of pages, but the code feels a bit hacky. It goes something like:

$times = 1;
if ( $somepages->count() < 5 ): ?>
  <?php $times = round(5 / $somepages->count(), 0, PHP_ROUND_HALF_UP); ?> 
<?php endif ?>
<?php for ($i=0; $i < ($times) ; $i++): ?> 
  <?php foreach ( $somepages as $apage): ?>
      ...
  <?php endforeach ?>
<?php endfor ?>

… and that still needs a way to limit $apage to 5

Perhaps I am missing a much simpler way of doing it ?

Thanks

Hm, I’m not very good with algorithms, this - while ugly - should work:

$limit = 5;
$pages = $page->children()->listed()->limit($limit);
$count = $pages->count();

if ($pages->isNotEmpty()) {
  $loops = ceil(5/$count); 
  for ($i = 1; $i <= $loops; $i++ ) {

    if($i > 1 && $i == $loops) { $limit = 5 - ($loops-1) * $count;  } 
   
    foreach ($pages->limit($limit) as $page) {
      echo $page->title() . '<br>';
    }
  }
}

Edited, because there was an error.

I bet there’s an easier way…

1 Like

And there is:

<?php 

$pages = $page->children()->listed();
$count = 0;
do {
  foreach ($pages as $page) { 
    echo $page->title() . '<br>';
    if (++$count > 4) { continue; }
  }
} while ($count < 5);

(thanks to @Adspectus)

(Whatever that is good for, to repeat the same stuff over again…)

1 Like

Ah, but of course, do while, danke!