Conditional pagination li's

I’ve noticed that must paginations in WordPress are constructed like this:

  <nav class="post-nav clear clearfix">

    <ul>
      <li class="previous"><?php echo get_next_posts_link( 'Previous', $the_query->max_num_pages ); ?></li>
      <li class="next"><?php echo get_previous_posts_link( 'Next' ); ?></li>
    </ul>

  </nav>

No matter if there’s a previous or next link, the li’s always show. Is there a way to wrap this li’s around a conditional to only show if “Previous” or “Next” posts exists?

Solutions Collecting From Web of "Conditional pagination li's"

Yes, but it is really more PHP than WordPress. You just need to reorder things and add some logic:

$next = get_next_posts_link( 'Previous', $the_query->max_num_pages );
$previous = get_previous_posts_link( 'Next' );
if(!empty($next)) {
  $links[] = '<li class="next">'.$next.'</li>';
}
if(!empty($previous)) {
  $links[] = '<li class="previous">'.$previous.'</li>';
}
if (!empty($links)) { ?>
  <nav class="post-nav clear clearfix">
    <ul><?php
      echo implode($links); ?>
    </ul>
  </nav><?php
}