Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output PHP array into unordered list [closed]

Tags:

php

New to php: I have a simple array:

$people = array('Joe','Jane','Mike');

How do I output this into a list?

<ul>
 <li>Joe</li>
 <li>Jane</li>
 <li>Mike</li>
</ul>

Any help or direction would be appreciated?

like image 691
cusejuice Avatar asked Feb 11 '13 14:02

cusejuice


2 Answers

You can use implode() and print the list:

echo '<ul>';
echo '<li>' . implode( '</li><li>', $people) . '</li>';
echo '</ul>';

Note this would print an empty <li> for an empty list - You can add a check in to make sure the array isn't empty before producing any output (which you would need for any loop so you don't print an empty <ul></ul>).

if( count( $people) > 0) {
    echo '<ul>';
    echo '<li>' . implode( '</li><li>', $people) . '</li>';
    echo '</ul>';
}
like image 164
nickb Avatar answered Sep 20 '22 14:09

nickb


Try:

echo '<ul>';
foreach($people as $p){
 echo '<li>'.$p.'</li>';
}
echo '</ul>';
like image 33
mallix Avatar answered Sep 17 '22 14:09

mallix