A Tip for Handling Arrays

On a quick vanity note, Chad Engle did an interview with me over on the DCTH site, so head over there and check that out!

Manipulate Arrays to Handle the First Element Differently

Arrays, though they’re incredibly useful, can also easily become confusing. This is especially true when dealing with multi-dimensional arrays, like a collection of entries from a database (a blog, for instance, would have at least two dimensions in an array of entries: each blog is an array of the different pieces of the blog, such as title, author, post date, and the entry itself; each entry array would then be stored in another array to keep the entries together).

Though confusing at first, getting comfortable with arrays can make a huge impact on your effectiveness as a programmer. Today, we’re going to look at using array_shift() to simplify array-handling when displaying multiple entries from a database.

The Ugly Way to Access the First Element

Often times when I’m dealing with a result set on a page, I end up needing to perform a special function for the first result, then continue on with the rest of the data set. This led to some awkward code, looking something like this:

/*
 * Loads the last 5 entries from the DB in an array with keys:
 *		'title'
 *		'author'
 *		'date'
 *		'entry'
 */
$entries = getEntriesFromDB($sql);

$html = "
	<h1> {$entries[0]['title']} </h1>
	<span>Posted by {$entries[0]['author']} on {$entries[0]['date']}</span>
	<p>{$entries[0]['entry']}</p>";

for($i=1, $n=count($entries); $i<$n; ++$i) {
	/*
	 * Creates a hyperlinked title
	 */
	$link = makeLinkedTitle($entries[$i]['title']);

	$html .= "<h2>{$entries[$i]['date']} - $link</h2>";
}

echo $html;

Note that I’m assuming the array returned from getEntriesFromDB() is numerically indexed, which, logically, is how the array would be created when the information is loaded from the database. This means the $entries array is indexed from $entries[0] (first entry array) to $entries[4] (the last of five loaded entries).

This code outputs one article, then four recent headlines preceded by their post dates. It looks something like this:

Sample Entry Title

Posted by Jason Lengstorf on April 14, 2009

This would be the actual entry, but for the sake of brevity, we’ll pretend it was more of a Twitter post.

April 10 – Another Entry
April 02 – An Entry About Coffee
March 28 – This One’s About Beer
March 26 – More of a Rant than an Entry

Optimizing the Code

By using array_shift(), we can clean up the syntax a little bit and create a snippet of code that is much easier to scan in the future.

/*
 * Loads the last 5 entries from the database
 */
$entries = getEntriesFromDB($sql);

/*
 * Removes the first array element and stores it in $first
 */
$first = array_shift($entries);

$html = "
	<h1> $first[title] </h1>
	<span> Posted by $first[author] on $first[date] </span>
	<p> $first[entry] </p>";

/*
 * Because the first element is no longer in the array, we can simplify
 * and use a foreach loop to move through the remaining entries
 */
foreach($entries as $e) {
	$link = makeLinkedTitle($e['title']);
	$html .= "
	<h2> $e[date] - $link </h2>";
}

echo $html;

The code above is much easier to read, which means future maintenance will be less painful.

Summary

Though it might not seem like much based on the example above, simplifying the handling of arrays can save hours of maintenance, especially when dealing with data sets that use arrays with ten, twenty, or even more elements per entry.

How do you handle multi-dimensional arrays? What do you wish you could do better with them? Let me know in the comments!