Skip to content

Instantly share code, notes, and snippets.

@absent1706
Last active May 31, 2017 22:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save absent1706/4e67bb0f274e24ae8ef1a5c3989bc80b to your computer and use it in GitHub Desktop.
Save absent1706/4e67bb0f274e24ae8ef1a5c3989bc80b to your computer and use it in GitHub Desktop.
PHP pagination class
<?php
class Pagination
{
public $page;
public $totalCount;
public $perPage;
public $hasNext;
public $hasPrev;
public $pageCount;
public $pages = [];
function __construct($page, $perPage, $totalCount)
{
$this->page = $page;
$this->totalCount = $totalCount;
$this->perPage = $perPage;
$this->pageCount = (int) ceil($totalCount / $perPage);
$this->pages = $this->_pages();
$this->hasNext = $page < $this->pageCount;
$this->hasPrev = $page > 1;
}
protected function _pages($left_edge=2, $left_current=2, $right_current=2, $right_edge=2)
{
$pages = [];
$previouslyWasNull = false;
foreach (range(1, $this->pageCount) as $num) {
$includeThisPage = ($num < $left_edge + 1) ||
(($num > $this->page - $left_current - 1) && ($num < $this->page + $right_current + 1)) ||
($num > $this->pageCount - $right_edge);
if ($includeThisPage) {
$pages[] = $num;
$previouslyWasNull = false;
}
elseif ($pages && !$previouslyWasNull) {
$pages[] = null;
$previouslyWasNull = true;
}
}
return $pages;
}
}
$pagination = new Pagination(2, 10, 1000);
var_dump($pagination); echo "\n";
$pagination = new Pagination(50, 10, 1000);
var_dump($pagination); echo "\n";
$pagination = new Pagination(98, 10, 1000);
var_dump($pagination); echo "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment