etrader Posted March 2, 2011 Share Posted March 2, 2011 I have a list generated from an array by foreach as foreach ($list_array as $item) { echo "$item<br />"; } This is a long list, how can I separate the list to different pages? I mean the simplest way to do so Link to comment https://forums.phpfreaks.com/topic/229422-paging-a-list-divide-to-separate-pages/ Share on other sites More sharing options...
Psycho Posted March 2, 2011 Share Posted March 2, 2011 <?php //Dummy array for testing $list_array = range(1, 500); //Define how many records you want on a page $records_per_page = 20; //Cacluate total records and total pages $total_records = count($list_array); $total_pages = ceil($total_records/$records_per_page); //Get/define current page $current_page = (int) $_GET['page']; if($current_page<1 || $current_page>$total_pages) { $current_page = 1; } //Get records for the current page $records = array_splice($list_array, ($current_page-1)*$records_per_page, $records_per_page); //Create ouput for the records of the current page $list_ouput = ''; foreach($records as $value) { $list_ouput .= "<li>{$value}</li>\n"; } //Create pagination links $first = "First"; $prev = "Prev"; $next = "Next"; $last = "Last"; if($current_page>1) { $prevPage = $current_page - 1; $first = "<a href=\"test.php?page=1\">First</a>"; $prev = "<a href=\"test.php?page={$prevPage}\">Prev</a>"; } if($current_page<$total_pages) { $nextPage = $current_page + 1; $next = "<a href=\"test.php?page={$nextPage}\">Next</a>"; $last = "<a href=\"test.php?page={$total_pages}\">Last</a>"; } ?> <html> <body> <h2>Here are the records for page <?php echo $current_page; ?></h2> <ul> <?php echo $list_ouput; ?> </ul> Page <?php echo $current_page; ?> of <?php echo $total_pages; ?> <br /> <?php echo "{$first} | {$prev} | {$next} | {$last}"; ?> </body> </html> Link to comment https://forums.phpfreaks.com/topic/229422-paging-a-list-divide-to-separate-pages/#findComment-1182054 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.