Technology Temerity

Lists and PHP Range

PHP

This article assumes LAMP or other PHP based web layout, and basic proficiency with PHP scripting.

Imagine you’ve just finished one of those simple but massive and often tedious alphabetical link lists or tables all of us in the web business are called upon to assemble at some point. You know the customer will appreciate the convenience of anchors and bookmark links. On the surface it would appear you have the less than fun choices of cobbling together a cumbersome loop to generate your links, or to type and double check each one by hand. Fortunately as of PHP version 4.0 there is a better option: Range.

Range is an oft overlooked and very useful function that will accept two bookends and return an array containing the in between values in order (bookends included).

For an example, to get the set of letter bookmark links at the top of this page, we could do it the hard way:

<a href="#A">A</a>
<a href="#B">B</a>
<a href="#C">C</a>
...

We could also write some home grown functions, probably involving a nested loop or two. But why do either when we could get the same result like this?

$markup = NULL;		// List markup.
$letter	= NULL;		// Letter placeholder.
$range  = array();	// Range array.

// Get range array, A to Z.
$range = range('A', 'Z');

// Loop range array.
foreach ($range as $letter)
{
	// Build link list markup.
	$markup .= '<a href="#'.$letter.'">'.$letter.'</a> '; 
} 
// Output markup 
echo $list; 

Simple, elegant, reusable, and best of all it’s far less prone to human error. Either the whole list works or none of it will, in which case you will know right away without the need to check each link individually.

Try your own experiments with range; it is quite versatile and extremely powerful in the right hands. It’s nothing you couldn’t do piecemeal or with custom solutions, it will most certainly simplify the process – freeing up your efforts for far more worthy causes.

Until next time!
DC

Author: Damon Caskey

Hello all, Damon Caskey here - the esteemed owner of this little slice of cyberspace. Welcome!

1 Comment

Leave a Reply