-
-
Save webdevid/37566b1e8370a1826bfc2969ca6e78e0 to your computer and use it in GitHub Desktop.
Simple PHP Pagination (one function)
This file contains 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 | |
/** | |
* | |
* Simple PHP Pagination | |
* | |
* @author Stichoza | |
* @link http://stichoza.com/ | |
* @email [email protected] | |
* @version 1.0 | |
* | |
* ---------------------------------------------------------------- | |
* | |
* Usage: $my_page_data = paginate($items, $current_page, $items_per_page); | |
* | |
* Return: | |
* Array( | |
* "prev_page" => Number: previous page; | |
* "curr_page" => Number: current page; | |
* "next_page" => Number: next page; | |
* "items" => Array: list of items; | |
* "items_curr" => Number: number of items on current page; | |
* "items_total" => Number: number of total items; | |
* "pages_total" => Number: number of total items; | |
* ); | |
* | |
* | |
* Real Example: | |
* $test_array = array(); | |
* for ($i=0; $i<561; $i++) $test_array[$i] = "Item #".$i; | |
* $paginated_slice = paginate($test_array, $_GET['page'], $_GET['items_per_page']); | |
* print_r($paginated_slice); | |
* | |
*/ | |
function paginate($items, $curr_page = 1, $ipp = 10) { | |
$items_total = count($items); | |
$pages_total = ceil($items_total / $ipp); | |
$next_page = $curr_page < $pages_total ? $curr_page + 1 : null; | |
$prev_page = $curr_page > 1 ? $curr_page - 1 : null; | |
$offset = ($curr_page - 1) * $ipp; | |
$items_slice = array_slice($items, $offset, $ipp); | |
return array( | |
"prev_page" => $prev_page, | |
"curr_page" => $curr_page, | |
"next_page" => $next_page, | |
"items" => $items_slice, | |
"items_curr" => count($items_slice), | |
"items_total" => $items_total, | |
"pages_total" => $pages_total | |
); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment