Skip to content

Instantly share code, notes, and snippets.

@Stichoza
Created November 9, 2012 15:05
Show Gist options
  • Save Stichoza/4046200 to your computer and use it in GitHub Desktop.
Save Stichoza/4046200 to your computer and use it in GitHub Desktop.
Simple PHP Pagination (one function)
<?php
/**
*
* Simple PHP Pagination
*
* @author Stichoza
* @link http://stichoza.com/
* @email admin@stichoza.com
* @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