how to make <ul> elements every two <li> using for loop?

Viewed 45

$arr = array("A","B","C","D","E","F","G");

how to use while or for loop make result like:

<ul>
   <li>A</li>
   <li>B</li>
</ul>
<ul>
   <li>C</li>
   <li>D</li>
</ul>
<ul>
   <li>E</li>
   <li>F</li>
</ul>
<ul>
   <li>G</li>
</ul>
1 Answers

This can be written quite concisely using array_chunk to split the input into smaller parts and implode to output the list:

$arr = array("A","B","C","D","E","F","G");

foreach (array_chunk($arr, 2) as $list) {
    echo '<ul><li>' . implode('</li><li>', $list) . '</li></ul>' . PHP_EOL;
}

Output:

<ul><li>A</li><li>B</li></ul>
<ul><li>C</li><li>D</li></ul>
<ul><li>E</li><li>F</li></ul>
<ul><li>G</li></ul>

Demo on 3v4l.org

Related