Paginate through array items


/ Published in: PHP
Save to your folder(s)

There are plenty of classes out there to paginate through database results, well, here's one to paginate through a static array of items. Written quite a few years ago, recently recovered from a crashed drive.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. class Paginate_Array
  4. {
  5.  
  6. var $_array;
  7. var $_per_page;
  8. var $_lpage;
  9. var $_offset;
  10.  
  11. var $_out = array();
  12.  
  13. function Paginate_Array($array, $offset = 0, $per_page = 3)
  14. {
  15. $this->_array = $array;
  16. $this->_per_page = $per_page;
  17. $this->_lpage = ceil(sizeof($this->_array) / $this->_per_page);
  18. $this->_offset = $offset;
  19. }
  20.  
  21. function getOffset()
  22. {
  23. return array_slice($this->_array, $this->_offset, $this->_per_page);
  24. }
  25.  
  26. function getPages()
  27. {
  28. for ($i=0; $i <= ($this->_lpage - 1); $i++) {
  29. $this->_out[$i+1] = $i * $this->_per_page;
  30. }
  31. return $this->_out;
  32. }
  33.  
  34. function _getLastOffset()
  35. {
  36. $_arr = $this->_out;
  37. return array_pop($_arr);
  38. }
  39.  
  40. function hasPrev($text)
  41. {
  42. return ($this->_offset > 0) ? $text : '';
  43. }
  44.  
  45. function hasNext($text)
  46. {
  47. return ($this->_offset < self::_getLastOffset()) ? $text : '';
  48. }
  49.  
  50. } // end class
  51.  
  52. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.