How can I improve this pagination algorithm in PHP?

I am working on a pagination algorithm in PHP. I can guess that he needs a place to improve, so I would like to think about how to improve it, whether it is cleaning up the code in terms of UI / UX, or anything else that you can think of.

The algorithm should output a pagination that looks like this:

1 2 3 ... 6 7 8 ... 97 98 99

or that:

1 2 3 4 5 ... 6 7 8 9 10

or that:

1 2 3

Here is my code:

<?php

if(!is_null($_GET['page'])) {
  $currentPage = $_GET['page'];
} else {
  $currentPage = 1;
}

if($pages != null) {
  echo 'Page: ';
}

// Less than 10 pages
if($pages <= 10) {
  for($page = 1; $page <= $pages; $page++) {
    echo '<a href="?page=' . $page . '">' . $page . '</a> ';
  }

// Greater than 10 pages, and we're somewhere in the middle of them
} elseif(($pages > 10) && ($currentPage > 4) && ($currentPage < $pages - 3)) {
  for($page = 1; $page <= 3; $page++) {
    echo '<a href="?page=' . $page . '">' . $page . '</a> ';
  }
  echo '... ';
  for($page = $currentPage - 1; $page <= $currentPage + 1; $page++) {
    echo '<a href="?page=' . $page . '">' . $page . '</a> ';
  }
  echo '... ';
  for($page = $pages - 2; $page <= $pages; $page++) {
    echo '<a href="?page=' . $page . '">' . $page . '</a> ';
  }

// Greater than 10 pages, and we're towards the end of the pages
} else {
  for($page = 1; $page <= 5; $page++) {
    echo '<a href="?page=' . $page . '">' . $page . '</a> ';
  }
  echo '... ';
  for($page = $pages - 5; $page <= $pages; $page++) {
    echo '<a href="?page=' . $page . '">' . $page . '</a> ';
  }
}
+3
source share
3 answers

I'm not sure my code is better than yours, but here's how I solved a similar problem.

div pages, , current. , .

function generate_pages($total,$current)
{ //Will generate pages and link to ?page=x when passed total pages to output
    if($total > 1)
    {
        $total=intval($total);

        $output='<div class="pages">';
        $current_page= (false == isset($current)) ? 1 : $current;
        for($page=1;$page<$total+1;$page++)
        {
            $lower=$current_page-3;
            $upper=$current_page+3;
            $special = ($page==$current_page) ? " class=\"current\"" : "";
            if(($page > $lower && $page < $upper) || $page < 2 || $page > ($total-1))
            {
                if($last_done_page+1 != $page) $output.= '... ';
                $output.='<a'.$special.' href="?page='.$page.'">'.$page.'</a>';
                $last_done_page=$page;
            }
        }
        $output.='</div>';
        return $output;
    }
}
+1

Source: https://habr.com/ru/post/1765483/


All Articles