Simple recursive PHP function to build a HTML <ul> list from array

   
    /**
     * @param $array
     * @return string
     */
    function buildHtmlList($array)
    {
        $out = '<ul>';
        foreach($array as $key => $v) {
            if( is_array($v) ) {
                $out .= '<li>' . $key ;
                $out  .= buildHtmlList($v);
                $out .= '</li>';
                continue;
            } else {
                $out .= '<li>' . $array[$key] . '</li>';
            }
        }
        $out .= '</ul>';
        return $out;
    }
 
     $array = array(
         'Item 1' => array(
             'Sub Item 1' => array(
               'Sub Sub Item 1'
             ),
         ),
         'Item 2' => array(
             'Sub Item 2' => array(
                 'Sub Sub Item 2'
           ),
         ),
         'Item 3',
     );

     $result = buildHtmlList($array);

Result

  • Item 1
    • Sub Item 1
      • Sub Sub Item 1
  • Item 2
    • Sub Item 2
      • Sub Sub Item 2
  • Item 3

Or with class names

    
/**
 * @param array $array
 * @param array $classes
 * @param int $level
 * @return string
 */
function buildHtmlList($array,$classes='',$level=0)
{
    $out = '<ul>';
    if(!empty($classes)) {
        $out = '<ul'.$classes[$level].'>';
    }
    foreach($array as $key => $value) {
        if( is_array($value) ) {
            $i = $level+1;
            $out .= "<li>" . $key ;
            $out .= $this->buildHtmlList($value,$classes,$i);
            $out .= '</li>';
            continue;
        } else {
            $out .= "<li>" . $array[$key] . "</li>";
        }
    }
    $out .= "</ul>";
    return $out;
}
$arr = array(
    'Item 1' => array(
        'Sub Item 1' => array(
            'Sub Sub Item 1'
        ),
    ),
    'Item 2' => array(
        'Sub Item 2' => array(
            'Sub Sub Item 2'
        ),
    ),
    'Item 3',
);
$classes = array(
    ' class="level-1"',
    ' class="level-2"',
    ' class="level-3"'
);
$result = buildHtmlList($arr,$classes);

Result

<ul class="level-1">
    <li>Item 1
        <ul class="level-2">
            <li>Sub Item 1
                <ul class="level-3">
                    <li>Sub Sub Item 1</li>
                </ul>
            </li>
        </ul>
    </li>
    <li>Item 2
        <ul class="level-2">
            <li>Sub Item 2
                <ul class="level-3">
                    <li>Sub Sub Item 2</li>
                </ul>
            </li>
        </ul>
    </li>
    <li>Item 3</li>
</ul>