0

I have 10 users in an array:

$array = array(
    "aaa",
    "bbb",
    "ccc",
    "ddd",
    "eee",
    "fff",
    "ggg",
    "hhh",
    "iii",
    "jjj",
);

And I want to display lists based on 5 or fewer users e.g.:

<ul>
    <li>
        <ul>
            <li>aaa</li>
            <li>bbb</li>
            <li>ccc</li>
            <li>ddd</li>
            <li>eee</li>
        </ul>
    </li>
    <li>
        <ul>
            <li>fff</li>
            <li>ggg</li>
            <li>hhh</li>
            <li>iii</li>
            <li>jjj</li>
        </ul>
    </li>
</ul>   

At the moment I have:

<ul>
<?php foreach($users as $user): ?>
    <li><?php echo $user ?></li>
<?php endforeach; ?>
</ul>

However I am not creating the inner uls. What is the best way to approach this? Using a for loop and counting out 5? Or is there a neater method?

3 Answers 3

2

Use array_chunk() to split an array into multiple arrays with a specified number of items.

<ul>
<?php
$users = array_chunk($array, 5);
foreach ($users as $user) {
    echo "<li><ul>";
    foreach ($user as $idv) {
        echo "<li>" . $idv . "</li>";
    }
    echo "</ul></li>";
}
?>
</ul>
Sign up to request clarification or add additional context in comments.

Comments

0

Look an alternative solution :)

<li>
 <ul>
     <?php
        echo '<li>'.join('</li><li>',array_slice($array,0,5)).'</li>';
    ?>
 </ul>
</li>

<li>
 <ul>
   <?php
       echo '<li>'.join('</li><li>',array_slice($array,5,10)).'</li>';
  ?>
</ul>
</li>

Comments

0
<ul>
<?php 
$lenght = count($users);
for( $i=0; $i<$lenght; $i++ ){
if( $i%5 == 0 ){ 
   echo '<li><ul>';
}
echo '<li>'.$users[0].'</li>';
if( $i%5 == 4 || ($i+1==$lenght) ){ 
    echo '</ul></li>';
}
}?>
</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.