php: build a HTML ul - li list from an associative array

2019-10-01 00:00:00 IN1 , 2023-04-10 14:16:30 IN1


Q: how to build an <ul>..<li> list on an array with php?

A: use the recursive function below for creation.

/**
 * @param array $aData
 * @return string $sMarkup Markup <ul>..<li> List
 */
function buildMarkupListTree($aData)
{
    if (false === is_array($aData))
    {
        return '';
    }

    $sMarkup = '<ul>';

    foreach ($aData as $sKey => $mValue)
    {
        $sMarkup.= '<li>' . trim($sKey);

        if (is_array($mValue))
        {
            $sMarkup.= buildMarkupListTree($mValue);
        }
        else
        {
            $sMarkup.= $mValue;
        }

        $sMarkup.= '</li>';
    }

    $sMarkup.= '</ul>';

    return $sMarkup;
}
This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".