I have actually been starting to use arrays a lot lately with some of the projects I have been working on.
The most recent application for an array in one of my projects is as follows:
I am designing a template system for one of the projects I am working on and I needed a simple way to output some rows from a db without all the clutter of a db connection, query, and while loop.
The cool thing about this is that I can call it as many times as I want because I create a function for it.
The Problem: Reduce db query/connection clutter by calling a function that in turn will populate an array with the desired information from the db.
Here’s all the crap you would want to put somewhere else, possibly in another file like functions.php:
// database information
$host = "";
$user = "";
$pass = "";
$db = "";
// connect to the database
mysql_connect($host, $user, $pass);
mysql_select_db($db);
// my little function call example
function get_links() {
// define the array to plot the links into.
// not entirely necessary but we don't want an error in our loop later on
// if we end up not returning any information
$links = array();
$query = "SELECT * FROM links";
$result = mysql_query($query);
while($row = mysql_fetch_object($result)) {
// define the id of our link from the current row
// assuming each link name is unique
$name = $row->name;
// define the url of our link from the current row
$url = $row->url;
// create a new element in our array
$links[$name] = $url;
}
return $links;
}
?>
Next we get to call the function and create our links!
// include our functions.php file
include "functions.php";
// call the function and grab our links!
$links = get_links();
// loop through the links and print them to the page
foreach($links as $name => $url) {
echo "" . $name . "";
}
?>
Notice how much less crap we need. This method is very useful if you plan on showing information multiple times on a specific page because all you have to do is loop through them again!
Hope this helps!
Regards,
Nick