Tag Archives: php pagination

PHP Pagination – Array Chunk Pagination

PHP Array Chunk Pagination - array_chunk <?php
//----------------------------------------------------------------------------
// Generate Sample Data
//----------------------------------------------------------------------------
foreach (range(1, 40) as $value)
{
$data[] = array(
'Product' => 'Product ' . $value,
'Price' => rand(10, 100),
'Quantity' => rand(1, 25)
);
}
//----------------------------------------------------------------------------
// Number Of Chunks
//----------------------------------------------------------------------------
$number_of_chunks = 4;
//----------------------------------------------------------------------------
// Break Array Into Chunks
//----------------------------------------------------------------------------
$data = array_chunk($data, $number_of_chunks);
//----------------------------------------------------------------------------
// Get Page Count
//----------------------------------------------------------------------------
$pagecount = count($data);
//----------------------------------------------------------------------------
// Make sure page is set and is numeric
//----------------------------------------------------------------------------
if (isset($_GET['p']) && (is_numeric($_GET['p'])))
{
if ($_GET['p'] > $pagecount)
{
die('<span style="color:#FF0000">Error: Page Does Not Exist</span>');
}
$i = $_GET['p'] - 1;
}
else
{
$i = 0;
}
//----------------------------------------------------------------------------
// Display array_chunk Data
//----------------------------------------------------------------------------
echo '<pre>';
print_r($data[$i]);
echo '</pre>';
//----------------------------------------------------------------------------
// Display array_chunk Pagination
//----------------------------------------------------------------------------
for ($i = 1; $i <= $pagecount; $i++)
{
echo "<a href='{$_SERVER['SCRIPT_NAME']}?p=$i'>$i</a> | ";
}