Jump to content

Writing a print function that draws from an array


alecsloman

Recommended Posts

Hey,

 

Not to abuse the good graces of the forum, but:

 

I have an array in (menus.php), and after including that to (index.php), I echo some values with the following:

 

foreach ($menu['main'] as $item) {

echo "<li>$item</li>";

}

 

That works fine, but the idea is that I want to automate this as much as possible. If I wanted to put that foreach statement into a function and place the function on (menus.php), how would I write it? And how would I call it in (index.php)?

 

My goal is to be at a point where I can just write something like "printmenu($menu[main]);

 

I keep looking at my book and various online tutorials, but...yeah, it just doesn't make sense.

 

Regards,

Alec

 

function printarray($array)
{
foreach ($array as $item) {

echo "<li>$item</li>";

}
}

//usage printarray($menu[main]);

That'd do it, but im sure others will come up with better ways.

Of course you could always just do:

print_r($menu[main],true);

But for that you'd need to have the elements include <li>*</li>

Put this in menus.php file

 

function printmenu($array)
{
    foreach($array as $value)
    {
        echo "<li>$value</li>";
    }
}

 

In index.php you would do this

include('menus.php');
printmenu($menu[main]);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.