0

I want to use a counter as a custom in my while loop, let's say we have a while loop < 21 I am trying to output something like this results:

1,2,
3,4,
5,6,7,
8,9,
10,11,
12,13,14,
15,16,
17,18,
19,20,21

I tried with writing these codes

<?php 

$counter = 1;

while ($counter <21) : 
    if( $counter == 1 || ($counter-1)%4 == 0 ) { 
        echo $counter."<br>";
    } 

    if( $counter == 2 || ($counter-2)%4 == 0 ) { ?>
    <div class="others">
    <?php } 
    if( $counter != 1 && ($counter-1)%4 != 0 ) { 
        echo $counter.',';
    }
    if( $counter%4 == 0 ) { ?>
        </div>
    <?php } 
    $counter++;
endwhile; 

But the output is like this

1
2,3,4,
5
6,7,8,
9
10,11,12,
13
14,15,16,
17
18,19,20,

SOLVED


@cannon gives a solution that works perfectly, but I want use the loop for calling database posts so that is why I resolve the problem...

<?php
$counter = 1;
$module =  7;
$i = 2;
$arr = [];
while ($counter <22) : 
    if( $counter == 1 || ($counter-1)% $module == 0  ) { 
        echo $counter.',';
    } 
    if(  $counter == 2  || ($counter-2)% $module    == 0 ) { 
        echo $counter.',<br>';
    } 
    if( $counter == 3 || ($counter-3)% $module == 0  ) { 
        echo $counter.',';
    } 
    if(  $counter == 4  || ($counter-4)% $module    == 0 ) { 
        echo $counter.',<br>';
    }
    $i = $i + $module;
    $arr[] = $i;
    if(!in_array($counter,$arr)){
        if( $counter == 5 || ($counter-5)% $module == 0 ) { 
            } 
        if( $counter != 1 && $counter != 2  && $counter != 3 && ($counter-1)% $module != 0  
        && $counter != 4  && ($counter-3)% $module != 0 && ($counter-4)% $module != 0  ) { 
            echo $counter.',';
        }
        if( $counter% $module == 0 ) { 
            echo '<br>';
        }
    } 
    $counter++;
endwhile; 
2
  • 1
    What's exactly "I am trying to output something like this results" ? what's the logical approach behind that output ? Commented Jun 30, 2018 at 23:46
  • I have posts from a database and I want to show posts in this manner in a grid... Commented Jun 30, 2018 at 23:49

1 Answer 1

2

You could try something like this, and it should work just as you described:

$counter = 1;
for($i = 1; $i < 21; $i++){
    echo $i . ',';

    if($counter % 6 == 0){
        echo ++$i . ',<br>';
    }
    elseif($counter % 2 == 0){
        echo '<br>';
    }
    $counter++;
}
Sign up to request clarification or add additional context in comments.

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.