8

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?

2
  • This is basic PHP. Use a loop. Commented Feb 11, 2013 at 14:44
  • php.net/foreach Commented Feb 11, 2013 at 14:49

5 Answers 5

25

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>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

I knew there had to be a concise way to do this.
6

Try:

echo '<ul>';
foreach($people as $p){
 echo '<li>'.$p.'</li>';
}
echo '</ul>';

Comments

0

Try this:

echo "<ul>";
foreach(people as $person){
  echo "<li>". $person ."</li>";
}
echo "</ul>";

Comments

0

You need to use loop to output array data as text.

There are multiple loops in PHP:

FOR

For will iterate $i (can be diferent variable and different change than iteration) and will end when the condition is not true anymore.

$people = array('Joe','Jane','Mike');
for($i=0; $i<count($people); $i++) {  //end when $i is larger than amount of people
    echo "  <li>{$people[$i]}</li>\n";
}

FOREACH

Very useful for unordered arrays - this loop will give you all values in the array as variable you want:

$people = array('Joe','Jane','Mike');
foreach($people as $human) {  //end when $i is larger than amount of people
    echo "  <li>$human</li>\n";
}

WHILE

Like FOR, loops while condition is met.

Comments

0
<?php

echo "<ul>";

foreach(array("test", "test2", "test3") as $string)) {
    echo "<li>".$string."</li>"
}

echo "<ul>";

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.