-2

sorry for my english i want echo limit element inside each div here is my code:

<?php 
for ($i=1;$i<=4;$i++) {
echo "<div class='container'>";
for ($j=1;$j<=8;$j++) {
  echo "content Number" . $j . "<br>";
}    
echo "</div>"
}
?>

my code doesn't work like i wish and i want result like this

<div class="container">
content Number 1
content Number 2
</div>
<div class="container">
content Number 3
content Number 4
</div>
<div class="container">
content Number 5
content Number 6
</div>
<div class="container">
content Number 7
content Number 8
</div>
3
  • You may be able to use a counter to determine when to start a new div or use array_chunk to split the array into groups of two. Commented Jan 10, 2020 at 13:29
  • I just answered the same thing, seconds apart. Commented Jan 10, 2020 at 13:29
  • very thanks my brothers Commented Jan 10, 2020 at 13:46

2 Answers 2

2

I'd be tempted to use the array_chunk method to explode an array into suitable pieces for display using simple foreach loops.

$max=4;
$bits=array_chunk( range( 1, ( $max * 2 ) ), 2 );

foreach( $bits as $pair ){
    echo '<div class="container">';
    foreach( $pair as $i )echo 'content Number '.$i.'<br />';
    echo '</div>';
}
Sign up to request clarification or add additional context in comments.

Comments

0
<?php 
$counter = 1;
for ($i=1;$i<=4;$i++) {
    echo "<div class='container'>";
    for ($j=1;$j<=2;$j++) {
        echo "content Number" . $counter . "<br>";
        $counter++;
    }
    echo "</div>";
}
?>

You were starting to count from 1 every time you started another .container div. You want one counter ($counter) instead. Then, loop once for the amount of containers, then again for the amount of content in each container!

3 Comments

Your output doesn't match what the OP is requesting.
Fixed, just put the div echos in the wrong place. My mistake
yeah you are right this my mistake thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.