-
-
Save synsa/306e80cf4a11e0c1798d537e1e85e4dc to your computer and use it in GitHub Desktop.
[PHP] Ultra simple pagination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
We want to display a lot of information to the screen = download a lot of HTML = lag. | |
LEt's go for a pagination ! | |
*/ | |
// Huge array with lot of dbig datas. | |
$my_huge_array = array(); | |
// Setting up pagination | |
$pagination = array( | |
'length' => isset($_GET['length']) ? (int) $_GET['length'] : 100, | |
'total' => sizeof($my_huge_array), | |
'currentPage' => isset($_GET['page']) ? (int) $_GET['page'] : 1, | |
); | |
$pagination['nbPages'] = ceil($pagination['total'] / $pagination['length']); | |
$pagination['offset'] = ($pagination['currentPage'] * $pagination['length']) - $pagination['length']; | |
// Paginated array | |
$paginated = array_slice($my_huge_array, $pagination['offset'], $pagination['length'], true); | |
// Paginator : | |
?> | |
<div> | |
<strong><?php echo sizeof($paginated) ?></strong> on | |
<strong><?php echo $pagination['total'] ?></strong> result<?php if($pagination['total'] > 1) echo 's' ?> | |
</div> | |
<ul class="pagination"> | |
<li> | |
<?php | |
if($pagination['currentPage'] > 1) | |
echo '<a href="'.$_SERVER['REQUEST_URI'].'&page=1">First</a>'; | |
else | |
echo '<span>First</span>'; | |
?> | |
</li> | |
<li> | |
<?php | |
if(($pagination['currentPage'] - 1) > 0) | |
echo '<a href="'.$_SERVER['REQUEST_URI'].'&page='.($pagination['currentPage'] - 1).'">Previous</a>'; | |
else | |
echo '<span>Previous</span>'; | |
?> | |
</li> | |
<?php | |
for($i = 1; $i <= $pagination['nbPages']; $i++) { | |
?> | |
<li<?php echo $i == $pagination['currentPage'] ? ' class="active"' : '' ?>> | |
<?php | |
if($i != $pagination['currentPage']) | |
echo '<a href="'.$_SERVER['REQUEST_URI'].'&page='.$i.'">'.$i.'</a>'; | |
else | |
echo '<span>'.$i.'</span>'; | |
?> | |
</li> | |
<?php | |
} | |
?> | |
<li> | |
<?php | |
if(($pagination['currentPage'] + 1) <= $pagination['nbPages']) | |
echo '<a href="'.$_SERVER['REQUEST_URI'].'&page='.($pagination['currentPage'] + 1).'">Next</a>'; | |
else | |
echo '<span>Next</span>'; | |
?> | |
</li> | |
<li> | |
<?php | |
if($pagination['currentPage'] < $pagination['nbPages']) | |
echo '<a href="'.$_SERVER['REQUEST_URI'].'&page='.$pagination['nbPages'].'">Last</a>'; | |
else | |
echo '<span>Last</span>'; | |
?> | |
</li> | |
</ul> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment