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

3 comments:

  1. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

    Java Training in Pune

    ReplyDelete
  2. BPO Solutions is a Pakistani based, RPO & BPO Company.

    ReplyDelete