Showing posts with label simple pagination. page pagination in array. Show all posts
Showing posts with label simple pagination. page pagination in array. Show all posts

Wednesday, May 20, 2015

PHP: Page pagination in array

Code snippet:
$page = !empty( $_GET['page'] ) ? (int) $_GET['page'] : 1;
$total = count( $yourDataArray ); //total items in array
$limit = 10; //per page    
$totalPages = ceil( $total/ $limit ); //calculate total pages
$page = max($page, 1); //get 1 page when $_GET['page'] <= 0
$page = min($page, $totalPages); //get last page when $_GET['page'] > $totalPages
$offset = ($page - 1) * $limit;
if( $offset < 0 ) $offset = 0;

$yourDataArray = array_slice( $yourDataArray, $offset, $limit );

echo 'Pages: ';
for($i = 1; $i <= $totalPages; $i++){
 
 if($i == $page){
  echo '<b>' . $i . '</b> ';
 }elseif($i != $page){
  echo '<a href="testpage.php?page=' . $i . '">' . $i . '</a> ';
 }
 
}
Output:
Pages: 1 2 3 4 

Refer: http://stackoverflow.com/questions/26451362/how-to-add-php-pagination-in-arrays