How to determine the first and last iteration in a foreach loop?
<p>I have three tables in a MySQL database.</p>

<ol>
<li>collection</li>
<li>category</li>
<li>subcategory</li>
</ol>

<p>I use the following function to retrieve data from these tables to display as a tree:</p>

<pre><code>function create_menu($params) {
    //retrieve menu items 
    //get collection 
    $collection = get('xxcollection') ;

    foreach($collection as $c) {
        echo '&lt;div class="parent" style="direction:rtl"&gt;';
        echo  '&lt;img src="../images/dtree/minus.gif" align="absmiddle" class="parent_item" id="minus" /&gt;
               &lt;img src="../images/dtree/base.gif" align="absmiddle" id="base"&gt;';
        echo $c['xcollectionname'];

        //get categories 
        $cat = get_where('xxcategory' , array('xcollectionid'=&gt;$c['xcollectionid'])) ; 

        foreach($cat as $item) {
            echo '&lt;div class="node" &gt;';
            echo  '&lt;img src="../images/dtree/plus.gif" align="absmiddle" class="node_item" id="plus" /&gt;
                   &lt;img src="../images/dtree/folder.gif" align="absmiddle" id="folder"&gt;';
            echo $item['xcatname'];

            $subcat = get_where('xxsubcategory' , array('xcatid'=&gt;$item['xcatid']));

            foreach($subcat as $val) {  
                echo  '&lt;div class="sub_node" style="display:none"&gt;' ; 
                echo  '&lt;img src="../images/dtree/join.gif" align="absmiddle" style="padding-left:2px;" /&gt;
                       &lt;a id="'.$val['xsubcatid'].'" href="javascript:void(0)" onclick="getProduct(this , event)" class="sub_node_links"&gt;';
                echo $val['xsubcatname'].'&lt;/a&gt;';
                echo '&lt;/div&gt;';
            }

            echo '&lt;/div&gt;';
        }

        echo '&lt;/div&gt;';
    }
}
</code></pre>

<ol>
<li>How can I determine the first and last iteration in the foreach loop?</li>
<li>Is it the correct way to retrieve data to be displayed as a tree?</li>
<li>I know it's not standard to use <code>&lt;div&gt;</code> tag to display a tree-like menu. I prefer to use nested <code>&lt;ul&gt;</code>s. However, I always have problems with <code>&lt;ul&gt;</code> in IE. I hope to get some advices or resources on how to use <code>&lt;ul&gt;</code> tags which work in different web browsers.</li>
</ol>
