Skip to content

Instantly share code, notes, and snippets.

@JSila
Created February 1, 2015 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JSila/50399652172414930af8 to your computer and use it in GitHub Desktop.
Save JSila/50399652172414930af8 to your computer and use it in GitHub Desktop.
pagination function
/**
* Paginates an array of data in accordance with how many items are on page
* and page currently viewed.
*
* @param array $data Array of data to paginate.
* @param int $perPage Number of items to display per page.
* @param int $currentPage Page number currently viewed.
* @return array
*/
function paginate(array $data, $perPage, $currentPage = null)
{
if ($currentPage <= 1 || count($data) < ($currentPage-1) * $perPage)
{
$currentPage = 1;
}
return [
'current_page' => $currentPage,
'max_pages' => (int) ceil(count($data)/$perPage),
'data' => array_slice($data, max($currentPage-1, 0) * $perPage, $perPage)
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment