PHP Pagination Example

PHP Pagination Example

Pagination is the process of grouping or dividing content into a number of pages. This works particularly well in terms of UX and when there is a lot of content as you really don’t want to force users to scroll through countless items in a single page. The pagination example below is written in PHP – Even though the code could practically be halved, I kept it as open and clean as possible for any beginners who wish to see how pagination works in the background.

Demo: http://jmcdermott.ie/examples/pagination/

pagination

The Code

The code below contains snippets of HTML and CSS, and of course PHP. I have created a single point of entry in the form of a PHP function called pagination() which allows you to pass in an array of values and the amount of items you want to display on the page. The script will then handle the rest.

<?php 

  // Populate seed values into array
  $values = array();
  for ($x = 1; $x < 112; $x++)   
  {  
    $values[] = $x." - Example"; 
  }
  
?>

<html>
  <head>
    <title>Easy PHP Pagination example</title>
    <style>
      html, body {
        margin: 50px;
        font-size: 16px;
        color: #505050; 
        font-family: sans-serif, arial;
      } 
      a {
        color: #999999;
        padding: 10px;
        border: 1px solid #afafaf;
        border-radius: 3px; 
        margin: 0px 5px 0px 0px; 
        text-decoration: none;  
      }
      a.selected {
        color: #ffffff;
        background-color: #97C4E5;	  
      } 
      #pageLinks {
        margin-top: 50px; 
      } 
    </style>
  </head>
  <body>
    <?php pagination($values, 12); ?>
  </body>
</html> 

<?php 

  /*
  |	----------------------------------------------------------------------
  |	OutputPageInfo(true if extra page, false if not, total num pages, total num items)
  |	----------------------------------------------------------------------
  */ 
  function outputPageInfo($extraPage, $totalPages, $totalItems)
  {
    if($extraPage)
    {
      print "<p><strong>Total Pages:</strong> ".($totalPages + 1)." | <strong>Total Items:</strong> ".$totalItems."</p>";
    } 
    else 
    {
      print "<p><strong>Total Pages:</strong> ".$totalPages." | <strong>Total Items:</strong> ".$totalItems."</p>"; 
    }
  }
  
  /*
  |	----------------------------------------------------------------------
  |	OutputItemCount(first item in the current view, last item in current view, total items in view)
  |	----------------------------------------------------------------------
  */
  function outputItemCount($firstItem, $lastItem, $totalItems)
  {
    if($lastItem > $totalItems + 1)
    {
      print "<p><strong>Displaying items:</strong> ".($firstItem + 1)." - ".$totalItems."</p>"; 
    }
    else 
    {
      print "<p><strong>Displaying items:</strong> ".($firstItem + 1)." - ".$lastItem."</p>"; 
    }
  }
  
  /* 
  |	----------------------------------------------------------------------
  |	OutputDesign(item output, true if valid page selected, false if not)
  |	----------------------------------------------------------------------
  */
  function outputDesign($output, $validPage)
  {
    if($validPage)  
    {
      print "<p> ".$output." </p>";  
    }
    else
    {
      print "<p> No items to display! </p>";
    }
  }
  
  /*
  |	----------------------------------------------------------------------
  |	Pagination(array of values, max number of items to display each page)
  |	----------------------------------------------------------------------
  */
  function pagination($array, $itemsPerPage)
  {
    //-------------------------------------------
    // Section 1 - Determine item/page information  
    //------------------------------------------- 
    
    // Set initial statistics 
    $totalItems = count($array);
    $totalPages = 0; 
    $extraPage = false; 
    $currentPage = 1; 
    
    // Calculate number of pages
    $totalPages = floor($totalItems / $itemsPerPage);  
    
    // Use modulus to see if there is any remainder of a direct division  
    if(($totalItems % $itemsPerPage) == 0) 
    {
      $extraPage = false;
    } 
    else
    { 
      $extraPage = true;  
    } 
    
    // Output page information (eg. Total Pages: 10 | Total Items: 111)
    outputPageInfo($extraPage, $totalPages, $totalItems);  
       
    //-------------------------------------------
    // Section 2 - Determine what items to show 
    //------------------------------------------- 
    
    if(isset($_GET['page'])) // If page number is set in URL
    {
      // Check if valid number 
      if(is_numeric($_GET['page']))
      { 
        $currentPage = $_GET['page'];
      }
      else
      { 
        $currentPage = 1;
      }
       
      $firstItem = 0;
      $lastItem = 0;
      
      if($currentPage == 1)
      {
        $firstItem = 0; // eg. item 0 
        $lastItem = $itemsPerPage; // eg. item 20 
        
        // Output item information (eg. Displaying items: 1 - 12) 
        outputItemCount($firstItem, $lastItem, $totalItems);			
        
        for ($x = $firstItem; $x < $lastItem; $x++)  
        { 
          if(array_key_exists($x, $array))  
          {
            outputDesign($array[$x], true); 
          }
        } 
      }
      else if($currentPage > $totalPages + 1)
      {
        outputDesign(0, false);   
      }
      else
      {
        $firstItem = ($currentPage -1) * $itemsPerPage; // eg. 1 * 20 = item 20
        $lastItem = $currentPage * $itemsPerPage; 		// eg. 2 * 20 = item 40
        
        // Output item information (eg. Displaying items: 1 - 12) 
        outputItemCount($firstItem, $lastItem, $totalItems);
         
        for ($x = $firstItem; $x < $lastItem; $x++)   
        {  
          // Check that the loop doesn't go past total amount of items! 
          if($x < $totalItems)  
          {
            // Check if value/index exists in array
            if(array_key_exists($x, $array))
            {
              outputDesign($array[$x], true); 
            } 
          } 
        } 	
      }
    } 
    else // If no page number is set in URL
    { 
      $currentPage = 1;
      
      if($totalItems < $itemsPerPage) 
      {
        print "<p><strong>Displaying items:</strong> 1 - ".$totalItems."</p>";  
      }
      else
      {
        print "<p><strong>Displaying items:</strong> 1 - ".$itemsPerPage."</p>";  
      }
      
      for ($x = 0; $x < $itemsPerPage; $x++)  
      { 
        // Check if value/index exists in array
        if(array_key_exists($x, $array))  
        { 
          outputDesign($array[$x], true); 
        }
      } 
    }
    
    //-------------------------------------------
    // Section 3 - Determine how many page links 
    //------------------------------------------- 
    
    print "<div id='pageLinks'>";
     
    if($extraPage)
    {
      for ($x = 1; $x < $totalPages + 2; $x++)  
      {
        if($currentPage == $x)
        {
          print "<a href='index.php?page=".$x."' class='selected'>".$x."</a>";  
        }
        else 
        {
          print "<a href='index.php?page=".$x."'>".$x."</a>";  	
        }
      }
    } 
    else 
    { 
      for ($x = 1; $x < $totalPages + 1; $x++)   
      {
        if($currentPage == $x)
        {
          print "<a href='index.php?page=".$x."' class='selected'>".$x."</a>";  
        }
        else 
        { 
          print "<a href='index.php?page=".$x."'>".$x."</a>";  	
        } 
      }
    } 
    
    print "</div>";
    
  }
   
?>

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>