0

So I am able to display 3 items per row in a webpage. However, the problem arises if there is an extra item. Say I have an array with items 1,2,3,4,5,6,7,8,9,10,11. I am able to display items 1 to 9. But unable to display 10 and 11 due to an index error, if I add 12, it will all be fine.

What I want is to display from this.

<div class='row-0'>
<p>1</p>
<p>2</p>
<p>3</p>
</div>
<div class='row-1'>
<p>4</p>
<p>5</p>
<p>6</p>
</div>
<div class='row-2'>
<p>7</p>
<p>8</p>
<p>9</p>
</div>

To this:

<div class='row-0'>
<p>1</p>
<p>2</p>
<p>3</p>
</div>
<div class='row-1'>
<p>4</p>
<p>5</p>
<p>6</p>
</div>
<div class='row-2'>
<p>7</p>
<p>8</p>
<p>9</p>
</div>
<div class='row-3'>
<p>10</p>
<p>11</p>
</div>

Here is my demo code so far:

<?php

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

$row=0;
$i=0;

while(true){
    echo "<div class='row-".$row."'>\n";
    while(true){
        echo "<p>".$arr[$i]."</p>\n";
        $i++;
        if($i%3===0){
            break;
        }
    }
    echo "</div>\n";
    $row++;
    if($arr[$i]==count($arr)){
        break;
    }
}
?>

Any tips? Thank you for reading.

diggledoot
  • 691
  • 8
  • 22
  • 1
    no need for two while loops, just use a for loop and use the modulo concept to close the div and start a new one – Kevin Apr 02 '21 at 05:14
  • 1
    Does this answer your question? [Split array into a specific number of chunks](https://stackoverflow.com/questions/15723059/split-array-into-a-specific-number-of-chunks) – nice_dev Apr 02 '21 at 06:02

1 Answers1

0

You should just check inside the array. And use 2 loops. The first loop for the number of rows. The second loop for the amount of elements and whether they exist in the array.

<?php

$numbers = array(1,2,3,4,5,6,7,8,9,10,11);
$number_of_rows = ceil(count($numbers) / 3);

$counter = 0;


for($i = 0 ; $i < $number_of_rows; $i++){
    echo "<div class='row-".($i)."'>\n";
        for($item = 3; $item > 0; $item--){
            if(array_key_exists($counter , $numbers)){
                echo "<p>".$numbers[$counter]."</p>\n";
            }
            $counter++;
        }
    echo "</div>\n";
}

?>