Saving Resources with phpCache

Now we come to the second array function I mentioned, array_walk(). While array_push() is great for inserting one row into an array at a time, array_walk() is perfect for running a function on one row in the array at a time.

To extract the data from your cached array, youíll need to use array_walk() where you want the data to appear on your page:

if($authors){ // if the array exists 
print("<p><h2>Authors</h2>"); 
// array walk the array $authors through the function print_authors(); 
array_walk($authors, 'print_authors');  
print("</p>"); 
}

The array_walk() function also takes two arguments, the first being the array you wish to use, and the second being the function you wish to pass each element of the array to. Also, as above, the "if statement" here is entirely optional if you know that $authors will always exist and contain an array. Itís included in this case because the "Authors" heading might look silly if indeed there were no authors (either because there were no authors in the database, or because the cache was lost or corrupted).

Now in the above example I use the function print_authors(). This is a user defined function you should define somewhere above in your PHP script. Some people like to put all of their functions in a separate file and then include it, which is a good solution if youíll be using the same function across multiple pages. Otherwise, the top of your PHP script is a good place to define functions.

In this specific example the function might look like this:

function print_authors($authors){ 
// extract  the data from our array 
$first_name = $authors["first_name"]; 
$last_name = $authors["last_name"]; 
$email = $authors["email"]; 
$id = $authors["id"]; 
// print the authorís information 
 print("<li><a href = \"mailto:$email\">$id: $last_name,  
$first_name</a><br/>"); 
}

Everything in the above function should be familiar. Here, we simply pull the database information out of the array we made above.

Implement it!

You should be able to implement this script on your site right now, if you havenít started already. If you refer to the example I outlined above, it should show you all the code needed to get this system up and running. If you happen to have any problems though drop in over at the forums and donít be afraid to ask for help.