How to add pagination in an array

I try many ways to add pagination. I tried to find and try to understand other ways to implement pagination, but none of them work.

This is how I created the Index page:

<?php $menuItems = array( "post1" => array( "title" => "Sample Title", "utime" => "M/d/Y", "content" => "<p>Body of the post</p>" ), "post2" => array( "title" => "Another Sample Title", "utime" => "M/d/Y", "content" => "<p>Content goes here...</p>" ), ); foreach ($menuItems as $contItem => $item) { ?> <li> <a href="dish.php?item=<?php echo $contItem; ?>"> <h1><?php echo $item["title"]; ?></h1> <small><?php echo $item["utime"]; ?></small> </a> </li> <?php } ?> 

I would like to know how I can split the pages of an array list. Thanks!

+14
arrays php pagination
source share
2 answers

u can use a simple PHP function called array_slice ()

 $menuItems = array_slice( $menuItems, 0, 10 ); 

show the first 10 items.

 $menuItems = array_slice( $menuItems, 10, 10 ); 

show next 10 items.

UPDATE:

 $page = ! empty( $_GET['page'] ) ? (int) $_GET['page'] : 1; $total = count( $yourDataArray ); //total items in array $limit = 20; //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 ); 

UPDATE # 2:

Pagination example:

 $link = 'index.php?page=%d'; $pagerContainer = '<div style="width: 300px;">'; if( $totalPages != 0 ) { if( $page == 1 ) { $pagerContainer .= ''; } else { $pagerContainer .= sprintf( '<a href="' . $link . '" style="color: #c00"> &#171; prev page</a>', $page - 1 ); } $pagerContainer .= ' <span> page <strong>' . $page . '</strong> from ' . $totalPages . '</span>'; if( $page == $totalPages ) { $pagerContainer .= ''; } else { $pagerContainer .= sprintf( '<a href="' . $link . '" style="color: #c00"> next page &#187; </a>', $page + 1 ); } } $pagerContainer .= '</div>'; echo $pagerContainer; 
+39
source share

Another viable option is to use array_chunk() :

 $pagedArray = array_chunk($originalArray, 10, true); $nthPage = $pagedArray[$pageNumber]; 
+10
source share

All Articles