ITT #13: Build a Menu with Recursive Functions
To continue my recent obsession with array
handling, I want to spend this week talking about recursive
functions and their application in dealing with arrays.
The goal of our exercise today is to build a menu, complete with
sub-menu, all based off one function that runs recursively.
What Is Recursion?
In computer science, recursion
is a concept in which a function can call itself. This is
similar to the idea of looping in PHP, but it provides an opportunity, in
the case of array handling, to add more fine-grain control into a
program.
On a basic level, recursion can be illustrated with the following code:
function plusOne($x)
{
if($x<10)
{
echo ++$x, "<br />";
plusOne($x);
}
else
{
echo 'Finished! <br />';
}
}
Calling this function will result in the following output:
1
2
3
4
5
6
7
8
9
10
Finished!
Obviously, the above could have been accomplished very simply with a
loop...
read more
ITT #12: Display Random Entries with PHP
I ran into an interesting problem while developing a new blogging system
recently where I needed to generate a subset of array elements in
random order.
A random subset of elements is useful for displaying a sampling of entries
that changes with every page load, such as four random blog entries, a
photo gallery that stays interesting even if new photos aren't uploaded,
or, if you want to use a sweet
content slider, you could show random portfolio or blog entry previews
and keep your slider fresh.
Defining the Problem
The Array
First things first, we need to know what we're dealing with. For the
purpose of this example, we'll be using a multi-dimensional
array that looks something like this:
$entries = array(
array(
'title' => 'Entry One',
'author' => 'Jason Lengstorf',
'date' => 'April...
read more
ITT #11: A Tip for Using Arrays
This week's Instant Tip Tuesday is a short one because I'm under some
pretty tight deadlines. I'm still looking for developers to help out by
guest blogging on Ennui Design, so contact me if you'd like to show
your developing chops!
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...
read more
- «
-
- 1
-
- »