Display subset image with if funtion

Hello Everyone.
I have a folder structure set up as:
0101/em.jpg
0102/hp.jpg
0102/em.jpg
0103/em.jpg

I am trying to display a section with just hp images and another with just em images. Currently I have this working (with the help of this forum)

<?php foreach ($page->children() as $child): ?>
<div><?php echo $child->uid() ?></div>
<div>   
<?php foreach($child->images()->filterBy('filename', '*=', 'HP') as $image): ?>
 <a href="<? echo $image->url() ?>"><img src="<? echo $image->url() ?>" alt="<? echo $image->title() ?>" /></a>
<?php endforeach ?>
 </div>
<?php endforeach ?>

This results in lots of empty sections and one hp image displaying. How can I have it display only the child folder with a hp image? if statement? hasImages()?

If I understand correctly, then try this:

<?php 
// fetch children with hp images only
$hpChildren = $page->children()->filter(function($child) {
  return $child->images()->filterBy('filename', '*=', 'HP')->count() > 0;
});

foreach ($hpChildren as $child): ?>
  <div><?php echo $child->uid() ?></div>
  <div> 
    <?php 
    $images = $child->images()->filterBy('filename', '*=', 'HP');
    foreach($images as $image): ?>
     <a href="<? echo $image->url() ?>"><img src="<? echo $image->url() ?>" alt="<? echo $image->title() ?>" /></a>
    <?php endforeach ?>
  </div>
<?php endforeach ?>