Copter Labs Copter Labs

Smart Design.

For Smart People.

Hold on... This isn't EnnuiDesign.com — What Gives?

It's been a long time coming, but Jason Lengstorf, formerly of Ennui Design, has expanded his team to include Drew Douglass, Rob MacKay, Henry Moran, and Tom Sturge.

It didn't feel right to keep the same name, so we decided to continue on as Copter Labs. You can expect the same great content under this new name!

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!

Date. 04/14/2009

Comments. 6

Category. PHP

Jason Lengstorf

Jason Lengstorf

Jason Lengstorf a turbogeek hailing from Portland, Oregon. He designs and develops websites using PHP, MySQL, JavaScript (jQuery), CSS, and HTML. He's written two books (PHP for Absolute Beginners [2009 Apress] and Pro PHP and jQuery [2010 Apress]), and he's written articles on development and design for Nettuts, CSS Tricks, and Smashing Magazine, among others.

Was This Post Helpful? Pass It On!

Share the Love

If this post taught you something, reminded you of something you had forgotten, or just made you feel good, there's really no better way to say "thank you" than passing it along to your friends.

Don't forget to like us on Facebook, join our newsletter, and/or subscribe to our RSS feed to make sure you hear about new posts first!

Join Our Gaggle of Geeks
* indicates required

Comments.

  1. Gravatar

    Stupid question, but is

    getEntriesFromDB($sql);

    Actually a function or is it just your shorthand for saying "make sure you get the entries?"

    PS - i'd be happy to do a blog post for you as a guest on jQuery if i Can think of a subject?

    Jack.

  2. Gravatar

    Great post. Can never get enough on arrays :)

    @Jack: From what i could tell getEntriesFromDB($sql) is a function that was described in the nettuts article "Add Power to Your PHP With Multi-Tiered Applications"

    http://net.tutsplus.com/tutorials/php/add-power-to-your-php-with-multi-tiered-applications/

  3. Gravatar

    @Jack and @Shane Sponagle:

    I probably should have been clearer on this; the getEntriesFromDB() function is a dummy function that would load your entries.

    I did show a way to write such a function in the article Shane mentioned on net.tutsplus.com/tutorials/php/add-power-to-your-php-with-multi-tiered-applications/

    @Jack:

    Send me an email, and we'll talk about ideas for an article!

    Thanks!

  4. Gravatar

    hollister uk sale

  5. Gravatar

    abercrombie and fitch uk outlet

  6. Gravatar

    hollister online shop

Join In.

Have something to say? By all means, speak up!

But first, a few rules:

  • Don’t be a jerk.
  • Use your real name, not your business name - this is a discussion, not a billboard.
  • Only <strong>, <em>, and <code> are allowed tags.
  • Wrap code samples in <code> tags.

Happy commenting!

Add a Comment