 <p>You can collect your list items and concat them using <a href="http://php.net/manual/en/function.implode.php" rel="nofollow">implode</a> method:</p> <pre><code>&lt;?php if (!empty($topmenu) &amp;&amp; !empty($menulist)) { $listItems = array(); foreach ($topmenu as $mainparent) { $arry = getmenuvalue($mainparent-&gt;id, $menulist, MAINURL); if (isset($mainparent-&gt;children) &amp;&amp; !empty($mainparent-&gt;children)) { $listItems[] = '&lt;li class="dropdown"&gt; &lt;a href="' . $arry['url'] . '" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"&gt;' . $arry['name'] . '&lt;span class="caret"&gt; &lt;/span&gt;&lt;/a&gt;&lt;/li&gt;'; } else { $listItems[] = '&lt;li&gt;&lt;a href="' . $arry['url'] . '"&gt;' . $arry['name'] . '&lt;/a&gt;&lt;/li&gt;'; } } echo implode('&lt;li&gt; | &lt;/li&gt;', $listItems); } ?&gt; </code></pre>