Last active
March 27, 2016 13:17
-
-
Save spikensbror/7080cfc31e6a47e23678 to your computer and use it in GitHub Desktop.
Pagination collapse algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$pages = 20; | |
$padding = 3; | |
$dedicated = 4; | |
function paginate($page) | |
{ | |
global $pages; | |
global $padding; | |
global $dedicated; | |
// Maximum amount of elements between the < and > elements. | |
$max = $dedicated + $padding * 2 + 1; | |
// Will the left and/or right side collapse? | |
$collapseLeft = $page - $padding - 1 > 1; | |
$collapseRight = $page + $padding + 1 < $pages; | |
// From which page do we start and where to we end? | |
$start = $collapseLeft ? $page - $padding : 1; | |
$end = $collapseRight ? $page + $padding : $pages; | |
// The offset which is used to extend the amount of elements if only one | |
// side is collapsed. | |
$stickyOffset = $max - $padding - ($end - $start); | |
// If the right side is not collapsed, we subtract the sticky offset from | |
// the starting point and if the starting point is lesser than the first | |
// page, we set it to 1. | |
// Likewise, if the left side is not collapsed, we add the sticky offset to | |
// the end point and if the end point is greater than the total amount of | |
// pages, we set it to the last page. | |
if (!$collapseRight && ($start -= $stickyOffset) < 1) | |
$start = 1; | |
else if (!$collapseLeft && ($end += $stickyOffset) > $pages) | |
$end = $pages; | |
// Below is just visual aid. | |
echo ' << '; | |
if ($collapseLeft) | |
{ | |
echo ' _01 '; | |
echo ' ... '; | |
} | |
for ($i = $start; $i <= $end; $i++) { | |
echo ' ', $i == $page ? 'X' : '_', str_pad($i, 2, '0', STR_PAD_LEFT), ' '; | |
} | |
if ($collapseRight) | |
{ | |
echo ' ... '; | |
echo ' _',$pages,' '; | |
} | |
echo ' >> '; | |
echo "\r\n"; | |
} | |
echo 'From page 1 to 7.', "\r\n"; | |
paginate(1); | |
paginate(2); | |
paginate(3); | |
paginate(4); | |
paginate(5); | |
paginate(6); | |
paginate(7); | |
echo "\r\n", 'From 20 to 14.', "\r\n"; | |
paginate(20); | |
paginate(19); | |
paginate(18); | |
paginate(17); | |
paginate(16); | |
paginate(15); | |
paginate(14); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment