ITT #6: PHP Arrays as Return Values

Arrays pack a ton of data into a small space

Use Arrays as Return Values to Turbocharge Your PHP

In this installment of Instant Tip Tuesday, we're going to talk about arrays in PHP. According to the PHP manual, an array is "an ordered map that associates values to keys." The benefit of using arrays is that we can pack a ton of data into one variable, which means we can pass that data back through a function.

What's So Cool About Passing Arrays?

I use arrays as return values to keep my processing of data separate from the formatting of said data. This is done in an effort to make code maintenance easier in the future. For example, look at the following code:

<html>
    <body>
<?php
    require_once '_db/mysql.php'; // Connect to the database

    $data = getDataFromDB("blog", 5); // returns latest 5 blog entries 
    for($i=0; $i<count($data); $i++) {
?>
        <h2> <?php echo $data[$i]['title']; ?> </h2>
        <p> <?php echo $data[$i]['body']; ?> </p>

<?php
    } // Close the for loop
?>
    </body> 
</html>

That's nice and easy, right? What we're doing is loading an array out of a function (which we'll write in just a minute), then looping through that array to format our data. This allows for extremely easy HTML formatting (notice we're formatting all 5 entries with just two lines of HTML), and allows us to completely change what information is loaded without having to deal with our HTML formatting at all.

NOTE: This is an extremely basic example, so the benefit of this technique might seem marginal. However, as you get into more complex data sets, this approach can literally save you hours. Trust me.

So how do we write the function to create the array?

Returning an Array

To return the array, we'll run a MySQL query, then loop through the result and store the information in an array to be used outside of the function, like so:

function getDataFromDB($page, $limit=10) 
{ 
    $data = array(); // Create an empty array to avoid a warning notice
 
    $query = "SELECT * FROM entryMgr WHERE page='$page' LIMIT $limit"; 
    $resource = mysql_query($query) or die(mysql_error()); 
    while($array = mysql_fetch_assoc($resource)) { 
        $data[] = array(
            'title' => $array['title'],
        	'body' => $array['body']
        );
    } 
    return $data; // Return the array 
}

The code above simply arranges our data into a multi-dimensional array, indexed numerically from 0, that can be returned through the function and easily looped through by our templating code.

In contrast to some of the other methods I've used over the years (formatting within the function that retrieves the data, writing a separate function to format that's called within the retrieval function, writing multiple queries to retrieve each piece of the array individually, etc.), using arrays as function return values seems like a no-brainer anymore, but it didn't occur to me for quite a while when I first started programming.

Calling All Geeks

I hope this post was merely a reminder of why you code the way you code, but to those of you who are new to this concept, I hope this can save you some of the frustration I suffered through as a beginning programmer. How do you save time while programming? It might be second-nature to you, but your tips could make a huge difference to someone who's just getting started. Share your thoughts in the comments!

Posted Mar 10, 2009 by Jason Lengstorf.
This entry is filed under instant tip tuesday, php, and programming.

Want more content like this? Subscribe for FREE!

Comments for This Entry

GravatarWill02:55PM on March 10, 2009

I have two thoughts:

Firstly, SELECT * is always a bad idea. I already wrote a post on it here:
http://www.willandbeyond.com/news/2008-07-25-mysql-select-all-is-bad-idea.php

In this case it's not quite as bad since you're picking out individual pieces of the array, instead of just pulling out the whole thing as I do in my example, but I would still steer away from SELECT *.

Secondly, unless you're working with an older version of PHP, shouldn't you be using mysqli commands? I realize that's not the focus of this post, but just another thought I had.

Nonetheless, great post, and definitely helpful for beginners.

GravatarWill02:58PM on March 10, 2009

On an unrelated manner, any chance that you could implement cookies so I don't need to re-enter comment info? Leaving the 'I am not a robot' part blank would be fine of course.

GravatarJosh03:56PM on March 10, 2009

@Will:
that would only matter if you only use fetch_row() and not fetch_assoc() or fetch_object(). The only time I pull in numeric arrays from a query are if it's only 1 or 2 values that i've defined in the query condition. Past that it's too arbitrary for anyone (and even yourself later on) to know what it is you're doing without checking all sorts of things.

PS. I don't use mysqli either.

GravatarJason Lengstorf04:29PM on March 10, 2009

@Will:
I agree with Josh that your argument against using "SELECT * FROM entries" would only cause problems if one wasn't using associative arrays.

However, I do agree that in a production environment, you should be using mysqli and specifying the column names you wish to retrieve.

@Josh:
I would recommend using mysqli in your future projects, at least for any piece of code that accepts user input.


Thanks for the comments! Oh, and about the cookies, it's on my to-do list. Soon!

GravatarJosh04:46PM on March 10, 2009

FWIW, WordPress still uses mysql (not mysql-improved), I'll assume for wider compatibility. I've got some scripts that use it and some that don't. I generally use mysql because I, sadly, have to deal with PHP4 and those that use it.

I'm not aware of any major speed improvements (past prepared statements) that come with mysql-improved. Unless someone can point me to a _decent_ comparison.

Post a Comment

Want to show your face? Get a gravatar!

ALLOWED TAGS: <tt><strong><em>