Php – Printing UL LI nested in Foreach Loop


i have an array structure like

[members] => Members List | 26
[member.php?id=3] => John | 26-26 
[member.php?id=4] => Alice | 26-26 
[member.php?id=5] => Michel | 26-26 
[news] => News details | 45
[alerts] > Alerts | 32

i traverse this using foreach loop. i want to print the Whole list as UL LI. The Members List will be an LI but when its childs comes (memeber.php?id=*) etc then it should inherit UL LI. I want the child to be in a nested LIs


$counter = 0;
foreach($array as $key => $values)
     if($counter == 0)
            echo "<ul>";
    if($key != "" && $key != "END")
            echo "<li>".$values."</li>";
    if($key == "END")
            echo "</ul>";

Best Solution

I don't know exactly the problem you have. But i think, you want something like this:

        <a href="members">Members List</a>
            <li><a href="member.php?id=3">John</a></li>
            <li><a href="member.php?id=4">Alice</a></li>
            <li><a href="member.php?id=5">Michel</a></li>
    <li><a href="news">News details</a></li>
    <li><a href="alerts">Alerts</a></li>

If yes, then i suggest you to change your array structure. Array can also be nested. And it will be easier if you have something like this:

$data = array(
    array('members', 'Members List', array(
        array('member.php?id=3', 'John'),
        array('member.php?id=4', 'Alice'),
        array('member.php?id=5', 'Michel'),
    array('news', 'News details'),
    array('alerts', 'Alerts')
  • $data is array.
  • Items in $data is array with at least 2 items. 1st item is href/url, 2nd item is label/text. If it has 3rd item, then it will be the children (subitems).
  • Subitems is composed similar to items, where 1st item is href/url, 2nd item is label/text.

Then, the following code will convert it to HTML:

echo '<ul>';
foreach ($data as $item) {
    // $item[0] -> href/url, $item[1] -> label/text, $item[2] -> subitems
    echo '<li>';
    echo '<a href="' . $item[0] . '">' . $item[1] . '</a>';

    if (isset($item[2])) { // if this item has subitems...
        echo '<ul>';
        foreach ($item[2] as $subitem) {
            // $subitem[0] -> href/url, $subitem[1] -> label/text
            echo '<li><a href="' . $subitem[0] . '">' . $subitem[1] . '</a></li>';
        echo '</ul>';

    echo '</li>';
echo '</ul>';