Fallback to image if gallery is empty

Hello,
I’m sure that the answer is really simply but I don’t know PHP and with Google or here in the forum I didn’t find the answer to my question:
What must I do to show my covers images if the gallery is empty?

For the gallery I have the following code:
<?php $gallery = $page->gallery()->toFiles(); foreach ($gallery as $image): ?>
<?= $image->crop(165, 120) ?>
<?php endforeach ?>

and if the gallery is empty I want to show only my cover images:
<?php $images = $page->cover()->toFiles(); foreach($images as $image): ?>
<?php $image ?>
<?php endforeach ?>

Thanks,
Sven

You can do that with an if statement:

<?php
$gallery = $page->gallery()->toFiles(); 
if ( $gallery->isNotEmpty() ) :
  foreach ($gallery as $image): 
?>
    <?= $image->crop(165, 120) ?>
  <?php endforeach ?>
<?php else: ?>
<?php 
  $images = $page->cover()->toFiles(); 
  foreach($images as $image): 
?>
    <?php $image ?>
  <?php endforeach ?>
<php endif; ?>

The code can be simplified if you do the same stuff with the images (i.e. if you crop no matter which files you use):

<?php
$images = $page->gallery()->toFiles()->isNotEmpty() ? $page->gallery()->toFiles() : $page->cover()->toFiles();

foreach ( $images as $image ) {
  echo $image->crop(165, 120);
}

Awesome. Thank You.