Possible to hide Page if no posts from a CPT?

So I’ve come up with a solution – although I am not sure if this is the best, as it outputs CSS, something I prefer not to do.

In the header.php of the theme:

<?php $published_posts = wp_count_posts('CPT1')->publish;
    if ( $published_posts == 0 ):
    echo '<style>.page-item-8{display:none;}</style>';
endif ?>

<?php $published_posts = wp_count_posts('CPT2')->publish;
    if ( $published_posts == 0 ):
    echo '<style>.page-item-9{display:none;}</style>';
endif ?>

This is for 2 separate CPTs. As you can see, it checks if the CPT has a post. If not – the CSS will display in the .

However, I am wondering if there may be a way to accomplish this same thing through the functions.php of the theme file?

Thanks!