Hari's Corner

Humour, comics, tech, law, software, reviews, essays, articles and HOWTOs intermingled with random philosophy now and then

Function to generate a pagination link list in PHP

Filed under: Tutorials and HOWTOs by Hari
Posted on Wed, Oct 1, 2008 at 12:04 IST (last updated: Sat, Apr 28, 2012 @ 09:01 IST)

When I was writing my blog software code, I came across a challenge peculiar to website scripts which require to display several pages of data. While actually retrieving the data for a particular page is simple enough using SQL queries (using SQL SELECT's LIMIT and OFFSET mechanism) generating a list of navigable links for each page of data is another cup of tea.

Let's assume that you want to generate a list of pages in PHP. E.g. You need to create a blog navigation toolbar, with links to each page on the footer.

The assumption is that you have hundreds of pages to display and you cannot display each page in the navigation toolbar, because that would become unwieldy. What you want is actually a list looking like this below (bolded item is current page):
Page: 1 2 3 4 5 ... 100

Or if the page is in the middle of the the navigation
1 ... 70 71 72 73 74 75 76 78 79 ... 100

If the page is at the end of this list
1 ... 92 93 94 95 96 97 98 99 100

This navigation scheme is not perfect, but it is adequate for most purposes. The following PHP function creates an array of navigable links which can be easily used to create such a pagination. This can be used as a generic pagination function, because it accepts all necessary parameters (including the base URL as well as the query string to use), total number of pages, current page and pagination limit. The pagination limits how many pages are actually shown around the current page.

<?php // Function to generate pagination array - that is a list of links
// for pages navigation
function paginate ($base_url, $query_str, $total_pages, 
                    $current_page, $paginate_limit)
{
    // Array to store page link list
    $page_array = array ();
    // Show dots flag - where to show dots?
    $dotshow = true;
    // walk through the list of pages
    for ( $i = 1; $i <= $total_pages; $i ++ )
    {
       // If first or last page or the page number falls 
       // within the pagination limit
       // generate the links for these pages
       if ($i == 1 || $i == $total_pages || 
             ($i >= $current_page - $paginate_limit && 
             $i <= $current_page + $paginate_limit) )
       {
          // reset the show dots flag
          $dotshow = true;
          // If it's the current page, leave out the link
          // otherwise set a URL field also
          if ($i != $current_page)
              $page_array[$i]['url'] = $base_url . "?" . $query_str .
                                         "=" . $i;
          $page_array[$i]['text'] = strval ($i);
       }
       // If ellipses dots are to be displayed
       // (page navigation skipped)
       else if ($dotshow == true)
       {
           // set it to false, so that more than one 
           // set of ellipses is not displayed
           $dotshow = false;
           $page_array[$i]['text'] = "...";
       }
    }
    // return the navigation array
    return $page_array;
} ?>

To use the function in a PHP page, you just have to simply walk through the array:
<?php // To use the pagination function in a 
// PHP script to display the list of links
// paginate 100 pages - current page is 50 and show
// 5 links around the current page
$pages = paginate ("myurl.php", "page", 100, 50, 5); ?>

<p>Pages: 
<?php 
// list display
foreach ($pages as $page) {
    // If page has a link
    if (isset ($page['url'])) { ?>
        <a href="<?php echo $page['url']?>">
		<?php echo $page['text'] ?>
	</a>
<?php }
    // no link - just display the text
     else 
        echo $page['text'];
} ?>
</p>

The output of the above code will be

Pages: 1 ... 45 46 47 48 49 50 51 52 53 54 55 ... 100

That's all. Hope you find it useful in your own PHP coding project. :)

14 comment(s)

  1. very good concept.. this is what i am seraching for a long time .. thanks a lot hari..

    Comment by jegan (visitor) on Thu, Oct 2, 2008 @ 17:32 IST #
  2. You're welcome, jegan. Glad to be of help. :D

    Comment by hari (blog owner) on Thu, Oct 2, 2008 @ 17:51 IST #
  3. I understood it, though I only skimmed it. I hate messing with code I'm unfamiliar with. Hopefully, I won't ever need to write any kind of paginating routines.

    Comment by RT Cunningham (visitor) on Thu, Oct 2, 2008 @ 18:07 IST #
  4. RT, if you're writing your own CMS or blog software, you'll need something like this - or at least a mechanism to navigate pages without too much clicking around.

    The logic is actually quite easy in the above code.

    Simply walk through the numbers 1 to max_page, displaying only the first and last pages and a preset number of pages before and after the current page.

    Comment by hari (blog owner) on Thu, Oct 2, 2008 @ 18:15 IST #
  5. I'm not sure where to place your code. I am new to PHP. My code:

    <?php

    $page=$_GET["page"]; //Get the page number to show
    If($page == "") $page=1;

    $limit = "10"; //total comments per page

    $total_comments = mysql_query("SELECT * FROM ". COMMENTS ."");
    $total =mysql_num_rows($total_comments);

    $total_pages=ceil($total_comments/$Limit);
    $offset = ($page - 1) * $Limit;

    for ($i=0; $i<=$total_pages; $i++) {
    $start = $limit * $i;

    $comments = mysql_query("SELECT * FROM ". COMMENTS ." LIMIT $start, $limit");

    echo '<div class="virtualpage">';

    while ($row = mysql_fetch_array($comments)) {


    $test = $row['name'];
    ?>

    <div><?php echo $test;?></div>

    <?php
    }
    echo '</div>';

    }
    ?>

    </div>

    Can you please give me an idea? Would your code work in a tabbed content without reverting to the first tab?

    Comment by Margaret (visitor) on Thu, Oct 22, 2009 @ 22:12 IST #
  6. Hi, Margaret. I'm not sure what your question is. The PHP code is purely to generate the simple HTML code required to display the links for pages in a website or blog (a.k.a. pagination).

    How you actually interpret the page numbers in links (the query string), retrieve that data in the particular page and display the page is another story which is not in the scope of this article. It can be almost anything, depending on the type of data - including SQL queries for databases.

    The code does not address anything else at all, actually...

    Comment by Hari (blog owner) on Sat, Oct 24, 2009 @ 15:55 IST #
  7. Thanks for the script, my pagination now have dots and is ready for a crazy number of pages which was not until now !

    Thanks again :p

    Comment by D F (visitor) on Fri, Apr 27, 2012 @ 23:09 IST #
  8. I knw this post is old, but i want to ask cant u put the two code together in just one fuction

    Comment by George (visitor) on Tue, Mar 19, 2013 @ 00:19 IST #
  9. I knw this post is old, but i want to ask cant u put the two code together in just one fuction


    The reason I separated the pagination function from the display code is for convenience. You needn't separate the two, but it is cleaner code to have the pagination logic separate from the display code.

    Comment by Hari (blog owner) on Tue, Mar 19, 2013 @ 09:02 IST #
  10. Nice and flexible script. What license is available?

    Comment by Akira (visitor) on Thu, May 8, 2014 @ 23:18 IST #
  11. Hi, Akira, you can use the above code in your scripts if you wish to. Though not explicitly licensed, I consider the above code as open source (BSD licensed) for the purpose of your question - feel free. :)

    Comment by Hari (blog owner) on Fri, May 9, 2014 @ 08:30 IST #
  12. Thank you hari this code saved a lot of my time.

    Comment by upendra (visitor) on Thu, Dec 4, 2014 @ 11:44 IST #
  13. No problem Upendra. Feel free :)

    Comment by Hari (blog owner) on Thu, Dec 4, 2014 @ 21:16 IST #
  14. :-)

    Comment by greg (visitor) on Fri, Jul 3, 2015 @ 10:25 IST #

Comments closed

The blog owner has closed further commenting on this entry.