计算页码,如果不是完整的第一页

Сreated a gallery with pagination and made it so that there were only 2 pictures on the first page, and 4 pictures on each subsequent page. This is just an example. New pictures appear automatically when they are added to the folder. There is one problem, in page navigation do not appear immediately, but only when there are more than two pages on the last page. I think this is somehow related to the fact that I removed 2 pictures from the first page. For these purposes, the variable $ xpp = 2 ;. How to make a calculation correctly, when on the penultimate page reach the limit $ per_page = 4; and to immediately appear the next page?

  $galleryDir = opendir("gallery");

  $restricted = array(".","..","thumbs","index.html","Thumbs.db");

  while(false !== ($filename = readdir($galleryDir))){
    if(!in_array($filename, $restricted))
      $files_array[] = $filename;
  }
  $count = 0;
  $per_page = 4;
  $total_pages = ceil(count($files_array)/$per_page);

  $page = (isset($_GET['page']))?(int)$_GET['page'] : 1;

  //if($page < 1 || $page > $total_pages) $page = 1;

  $xpp = 2;
  $limit = $per_page - ($page<2)*$xpp;
  $start = ($page - 1) * $per_page - ($page>1)*$xpp;
?>
<!DOCTYPE html>
<html>
<head>
<title>Loop Files in PHP</title>
</head>
<body>
<h3>Viewing page <?php echo $page; ?> of <?php echo $total_pages; ?></h3>
<div class="gallery-holder">
  <?php for($i = $start; $i < count($files_array); $i++){$count++;?>
    <a href="gallery/<?php echo $files_array[$i];?>">
     <img src="gallery/<?php echo $files_array[$i];?>">
    </a>
  <?php

  if($limit==$count)break;}
  ?>
</div>
<div class="nav" style="text-align:center;">
    <?php if($page>1){?>
      <a href="?page=<?php echo 1;?>">&larr; First</a>
      <a href="?page=<?php echo ($page - 1);?>">&larr; Prev</a>

    <?php }
      for($i=1;$i<=$total_pages; $i++)
      {
    ?>
          <a href="?page=<?php echo $i;?>"><?php echo $i;?></a>
    <?php 
      }
    ?>
      <?php if($total_pages > $page) { ?>
      <a href="?page=<?php echo ($page + 1); ?>">Next &rarr;</a>
      <a href="?page=<?php echo $total_pages;?>">Last &rarr;</a>
      <?php } ?>
</div>
</body>
</html>```