Skip to content

Instantly share code, notes, and snippets.

@Sannis
Created June 25, 2012 09:07
Show Gist options
  • Save Sannis/2987539 to your computer and use it in GitHub Desktop.
Save Sannis/2987539 to your computer and use it in GitHub Desktop.
Pagination HTML generator
<?php
/**
* Generates array with pages numbers for pagination
*
* @param int $current Current page
* @param int $total Total pages
* @param int $edgeSize
* @param int $midSize
*
* @return array
*/
function pageNavigationArray($current, $total, $edgeSize, $midSize)
{
$current *= 1;
$total *= 1;
if ($total < 1) {
$total = 1;
}
if ($total == 1) {
return array();
}
if ($current > $total) {
$current = $total;
}
$edgeSize = 0 < (int) $edgeSize ? (int) $edgeSize : 1; // Out of bounds? Make it the default.
$midSize = 0 <= (int) $midSize ? (int) $midSize : 2;
$navArray = array();
$dots = false;
for ($n = 1; $n <= $total; $n++) {
if ( $n == $current ) {
$navArray[] = $n;
$dots = true;
} else {
if ($n <= $edgeSize || ($current && $n >= $current - $midSize && $n <= $current + $midSize) || $n > $total - $edgeSize) {
$navArray[] = $n;
$dots = true;
} elseif ($dots) {
$navArray[] = 0;
$dots = false;
}
}
}
return $navArray;
}
/**
* Generates text for pagination
*
* @param int $current Current page
* @param int $total Total pages
* @param string $thisPageTags
* @param string $otherPageTags
* @param string $spaceTags
* @param bool $showPrevNext
*
* @return array
*/
function pageNavigation($current, $total, $thisPageTags = "%", $otherPageTags = "%", $spaceTags = "..", $showPrevNext = false)
{
// Constants
$edgeSize = 4;
$midSize = 2;
// Sanitize input
$current *= 1;
$total *= 1;
if ($total < 1) {
$total = 1;
}
if ($total == 1) {
return '';
}
if ($current > $total) {
$current = $total;
}
$navArr = pageNavigationArray($current, $total, $edgeSize, $midSize);
$out = '';
if ($showPrevNext && ($current > 1)) {
$out .= str_replace(array("%title%", "%"), array("Prev", $current - 1), $otherPageTags);
}
for($i = 0; $i < count($navArr); $i++) {
if ($navArr[$i] == 0) {
$out .= $spaceTags;
} else {
if ($navArr[$i] == $current) {
$out .= str_replace(array("%title%", "%"), array($current, $current), $thisPageTags);
} else {
$out .= str_replace(array("%title%", "%"), array($navArr[$i], $navArr[$i]), $otherPageTags);
}
}
}
if ($showPrevNext && ($current < $total)) {
$out .= str_replace(array("%title%", "%"), array("Next", $current + 1), $otherPageTags);
}
return $out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment