Quick Cascading Menu in PHP

How often have you wanted to build a tree-type menu but didn't know quite where to start or how to go about it? The following very simple function turns a multi-dimensional array into a neat HTML tree!

Setup

First thing you have to do is setup your menu structure. The format is an array, with one entry for each link. Each entry should have a key of the link text, and a value of the page to link to. The following is a two-level sample.

<?
$menu = array(  "Home"     => "index.php",
                "About"    => "about.php",
                "More"     => "page2.php",
                "Parent 1" => array(    "Child 1" => "page3.php",
                                        "Child 2" => "page4.php",
                                        "Child 3" => "page5.php"
                                    ),
                "Another Page" => "blah.php"
            );
?>

The Menu Builder

The following function processes your menu array to build it into a nice looking HTML menu.

<?
function tree_menu($array, $indent=0) {
    $prefix = "";
    for ($i=0; $i<$indent; $i++) {
        $prefix .= "    ";
    }
    while (list ($key, $value) = each($array)) {
        if (is_array($value)) {
            echo $prefix . $key . "<br>";
            tree_menu($value, $indent + 1);
        } else {
            echo $prefix . "<a href='" . $value . "'>" . $key . "</a><br>";
        }
    }
}
?>

Pulling it all together

Put the above code snippets into a PHP file, and at the bottom just have a single PHP snippet:

<?
tree_menu($menu);
?>

Voila! A nice array-driven menu system!