1

I have an array; the following

$arr = array(
    '1', 
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
);

and I want to print something like

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

My code only print the first 3

for($m = 0; $m < 9; $m++){
echo "<ul>";

for($i = 0; $i <3; $i++){
    echo "<li>";
    echo $arr[$i];
    echo "</li>";
}

echo "</ul>";
}

Really appreciate it!

0

3 Answers 3

2

You can use php array_chunk($arr,number of chunk)

$arr = array( '1', '2', '3', '4', '5', '6', '7', '8', '9');
    $chunkArray = array_chunk($arr,3);

    foreach ($chunkArray as $key => $value) {
        echo '<ul>';
        foreach ($value as $key1 => $value1) {
            echo '<li>'.$value1.'</li>';
        }
        echo '</ul>';

    }
Sign up to request clarification or add additional context in comments.

1 Comment

with closing </li>.
1

One option is to use modulo (%) like:

$arr = array(
    '1', 
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
);


$perGroup = 3;

for($m = 0; $m < count($arr); $m++){
    if ( $m % $perGroup === 0 ) echo "<ul>";

    echo "<li>";
    echo $arr[$m];
    echo "</li>";

    if ( $m % $perGroup === ( $perGroup - 1 ) || $m === (  count($arr) - 1 ) ) echo "</ul>";
}

This will result to:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
<ul>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>
<ul>
  <li>7</li>
  <li>8</li>
  <li>9</li>
</ul>

Comments

0

Try This

$arr = array(
        '1', 
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
    );
    $i=0;
    echo "<ul>";

    foreach($arr as $value)
    {
        if($i ==3)
        {
            echo "</ul><p></p><ul>";
            $i=0;  
        }

        echo "<li>";
        echo $value;
        echo "</li>";   

        $i++;
    }
    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.