simple php paging

motivation:
to create a simple template for paging through a group of items

usage:
copy the code below into a file, put it on yo’ server, eg pager.php, and start hitting it in the browser. For example, a good place to start is example.com/pager.php?page=1

notes:
in the interest of simplicity, the code assumes you won’t request more items than exist in the array. If you do, eg page = 5, at 5 items per page, when you only have 10 items in the array, you’ll get funky behavior. If you want to handle this case, check for the existence of items in the html template html.

<?php
$items = array(1,2,3,4,5,6,7,8,9,10,11,12);
$limit = 5;

$qty_items = count($items);
$qty_pages = ceil($qty_items / $limit);

$curr_page = isset($_GET['page']) ? $_GET['page'] : 1;
$next_page = $curr_page  1 ? $curr_page - 1 : null;

$offset = ($curr_page - 1) * $limit;
$items = array_slice($items, $offset, $limit);

?>

.curr{
    border:1px solid #ddd;
    padding:3px;
}


<ul>
    
        <li></li>
    
</ul>


    &lt;a href=&quot;pager.php?page="&gt; &lt;&lt; </a>

&lt;? for($i = 1; $i 
    &lt;a href=&quot;pager.php?page=" class=""&gt;</a>


    &lt;a href=&quot;pager.php?page="&gt; &gt;&gt; </a>

3 thoughts on “simple php paging

Comments are closed.