Erik's blog

Code, notes, recipes, general musings

simple php paging

with 2 comments

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&#91;'page'&#93;) ? $_GET&#91;'page'&#93; : 1;
$next_page = $curr_page < $qty_pages ? $curr_page + 1 : null;
$prev_page = $curr_page > 1 ? $curr_page - 1 : null;

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

?>
<style>
.curr{
    border:1px solid #ddd;
    padding:3px;
}
</style>

<ul>
    <? foreach($items as $item): ?>
        <li><?= $item ?></li>
    <? endforeach ?>
</ul>

<? if($prev_page): ?>
    <a href="pager.php?page=<?= $prev_page ?>"> << </a>
<? endif ?>
<? for($i = 1; $i <= $qty_pages; $i++): ?>
    <a href="pager.php?page=<?= $i ?>" class="<?= ($i == $curr_page) ? 'curr' : '' ?>"><?= $i ?></a>
<? endfor ?>
<? if($next_page): ?>
    <a href="pager.php?page=<?= $next_page ?>"> >> </a>
<? endif ?>
Advertisements

Written by Erik

January 11, 2009 at 12:35 am

Posted in code

Tagged with ,

2 Responses

Subscribe to comments with RSS.

  1. thanks!

    te

    December 28, 2010 at 12:54 am

    • I’m glad you found it helpful 🙂

      Erik

      December 28, 2010 at 11:22 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: