Multiple variables in foreach loop

Hello everyone!
I have a question concerning the foreach loop in kirby (but it’s probably more a lack of php knowledge…).

I’m trying to shuffle and list the titles of all the files AND all the subpage in the same foreach loop.
Of course I could write two different foreach loop but since I want to shuffle all the content, it has to be in the same loop.

here’s an exemple of what i’m trying to achieve. My content file would be like :

  • /fruits
    (some content)
  • /vegetables
    (some content)
  • /drinks
    (some content)
  • restaurant.jpg
  • restaurant.jpg.txt
  • menu.jpg
  • menu.jpg.txt
  • sky.jpg
  • sky.jpg.txt
  • page.txt

I would like to return :


Is it possible to add two variables in the same foreach loop ?
I would guess :

$subpages = $page->children()->title();
$images = $page->myimages()->tofiles();

<?php foreach(($subpages + $images)->shuffle()  as $item): ?>
	<h1><?= $item->title() ?></h1>
<?php endforeach ?>

I know the ($subpages + $images) doesn’t work, i think i have to do an array but I don’t know how.

Any idea ?
Thanks !

$subpages = $page->children()->title();
$images     = $page->myimages()->tofiles();
$collection = new Collection();
$collection = $collection->shuffle();

If your files don’t have a title, you might want to check the type of each item in the collection before outputting them, e.g.

foreach($collection as $item) {
  if($item instanceof Kirby\Cms\Page) {
    echo  $item->title();
  } else {
    echo $item->filename();

Disregard. @pixelijn’s approach is much better.

Thanks a lot ! it works :slight_smile:

Hello Sebastian,
Thanks ! the pixelijn’s solution worked for me :slight_smile:

1 Like