Tiffany B. Brown

A web log about web development and internet culture with frequent detours into other stuff.
One year later
Thoughts on Barack Obama and Choosing Blackness

Simple pagination for arrays with PHP 5

While working on a recent project, I had to build a feature that displayed a list of files available in a directory. A simple way is just to use scandir() and a foreach loop to spit out a pretty list.

There’s a small problem though: long lists aren’t all that user friendly. I decided instead to paginate the results. Here’s one way to do it using PHP 5:

Step 1: Read the directory

/*
 * scandir is only available in PHP 5 or higher.
 * It returns an array of ALL available files in the
 * specified directory
*/

$allfiles = scandir('/directory/to/scan/');

Now we don’t want to display every file. Some files are system files. Some files may not be the right format. Here, we’re going to eliminate any file name that starts with a period.

# intialize a new array of files that we want to show
$goodfiles = array();

# add a file to the $goodfiles array if its name doesn't begin with a period
foreach($allfiles as $f){
	if(strpos($f,'.')!==0){
		array_push($goodfiles,$f);
	}
}

Step 2: Split it! Split it good!

Now we get to the heart of things: determining how many pages there will be and how many items we’ll show per page. It’s remarkably simple thanks to PHP’s array_chunk() function. The array_chunk function takes two parameters: the array that you want to split, and the number of units that should be in each set.

$pages = array_chunk($goodfiles, 5);

This produces a multidimensional array which, if we print_r it, looks a bit like this (let’s assume we have 13 files in the directory).

Array
(
    [0] => Array
        (
            [0] => About_RFSB06WEB.flv
            [1] => Kids_Excited.flv
            [2] => Kids_Start_Run.flv
            [3] => Kids_start.jpg
            [4] => Kids_start_sm.jpg
        )

    [1] => Array
        (
            [0] => image01.jpg
            [1] => image02.jpg
            [2] => image03.jpg
            [3] => image04.jpg
            [4] => image05.jpg
        )

    [2] => Array
        (
            [0] => image06.jpg
            [1] => image07.jpg
            [2] => image08.jpg
        )
)

Each parent array is a page. Each child array is the content for that page. Now we just have to specify which page we want to view. In this example, we’re going to pass the desired page to the script as part of a query string — showfiles.php?showpage=1.

Step 3: Linking up

So now that our array is all split and chunked, we can build our page links. As I explained earlier, using array_chunk() creates our ‘pages.’ To build our pagination navigation, then, we just need to create as many links as there are pages. Let’s do this with a for loop.

<? for($i=1; $i< count($pages)+1; $i++): ?>
     <a href="showfiles.php?showpage=<? echo $i;?>"<<? echo $i; ?></a>
<? endfor; ?>

Remember that we’re doing a page count, so we want to start at one (not zero). Now it’s just a matter of grabbing the variable’s value to specify which array to show. We’re grabbing that value from the query string in the URL.

$pgkey = (int)$_GET['showpage']; // forces $_GET['showpage'] to be an integer
$pages[$pgkey];

If you want to highlight which page the user is on, add if / else logic to check whether the value of $i is the same as the value of $_GET['showpage'] and apply a style or CSS class name.

Step 4: Showing the files

The final step is to show the files on each page. Simply use a foreach loop.

foreach($pages[$pgkey] as $file){ echo $file.'<br />'; }

This is a technique that you could conceivably use to display any array data across pages.

Share this entry:
  • TwitThis
  • Digg
  • Technorati
  • del.icio.us
  • Ma.gnolia
  • Mixx
  • NewsVine
  • Reddit
  • StumbleUpon
  • TailRank
  • Global Grind
  • YahooMyWeb
  • Google
  • Live
  • LinkedIn
  • MySpace
previous post: One year later
next post: Thoughts on Barack Obama and Choosing Blackness