0

Let's say I have an array containing these items:

$test = array(Item1, Item2, Item3, Item4, Item5, Item6, Item7, Item8, Item9);

How can I print this structure using for, or foreach?

<ul>
    <li>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
    </li>
    <li>
        <ul>
            <li>Item 5</li>
            <li>Item 6</li>
            <li>Item 7</li>
            <li>Item 8</li>
        </ul>
    </li>
    <li>
        <ul>
            <li>Item 9</li>
        </ul>
    </li>
</ul>
2
  • Do you know for- and while-loops and echo? Commented Feb 28, 2012 at 9:02
  • yes, I cand use that too Commented Feb 28, 2012 at 9:27

3 Answers 3

4

You could split the array into chunks, using array_chunk():

$chunks = array_chunk($test, 4);

This will give you an array containing sub-arrays of 4 items each. You could then loop through these to create the list items:

<ul>
    <?php foreach ($chunks as $chunk): ?>
        <li>
            <ul>
                <?php foreach ($chunk as $item): ?>
                    <li><?php echo htmlspecialchars($item) ?></li>
                <?php endforeach ?>
            </ul>
        </li>
    <?php endforeach ?>
</ul>
Sign up to request clarification or add additional context in comments.

Comments

1

use array_chunk to split your values

$test = array('Item1','Item2','Item3','Item4','Item5','Item6','Item7','Item8','Item9');

$chunk = array_chunk($test, 4);

echo '<ul>';
foreach($chunk as $pieces) {
    echo '<li>';
    echo '<ul>';
    foreach($pieces as $item) {
        echo '<li>'.$item.'</li>';
    }
    echo '</ul>';
    echo '</li>';
}
echo '</ul>';

Comments

0

Try this

<?php
    $test = array(Item1, Item2, Item3, Item4, Item5, Item6, Item7, Item8, Item9);
    $ChunkedTestarray = array_chunk($test, 4);
    echo "<ul>";
    foreach($ChunkedTestarray as $Data) {
        echo "<li><ul>";
        for ($i = 0; $i <= count($Data)-1;) {
            echo "<li>".$Data[$i]."</li>";
            $i++;
        }
        echo "</ul></li>";
    }
    echo "</ul>";
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.