Ajendra Panwar
Ajendra Panwar

Reputation: 103

add a closing html tag for each 3rd and 4th item in a loop

I have a design which i need to impletement inside a foreach loop.

enter image description here

I need to add the html closing tag for every 3rd and 4th value in the loop. anyone have a solution?

example array:

$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);

condition need to added inside foreach or for loop I am trying to achive it like this:

$tmp = '';
$count = 1;
foreach($array as $val){

    if($tmp == 1){
        echo "Second Box".$val."<br>";
        $tmp=0;
        $count++;
    }else{
        if($count % 2 == 0){
            echo "Second Box".$val."<br>";

            $tmp = 1;
        }else{
            echo "First Box".$val."<br>";
        }
    }
    $count++;
}

out put

First Box1
Second Box2
Second Box3

First Box4
Second Box5
Second Box6

First Box7
Second Box8
Second Box9

First Box10
Second Box11
Second Box12

First Box13
Second Box14
Second Box15

First Box16
Second Box17
Second Box18

First Box19
Second Box20
Second Box21

out put of the above comes like this: enter image description here

Upvotes: 0

Views: 51

Answers (1)

user13457138
user13457138

Reputation:

This does it...

Set $f to first block amount, and $s to second....

$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);

$f = 3;
$s = 4;
$c = $f;
$i = 0;
foreach($array as $val){

    $i = $i + 1;
    echo $val;

    if ($i % $c == 0) {
        echo '<br>';  // add your row html tags here
        if ($c == $f) {
            $c = $s;
        } else {
            $c = $f;
        }
        
        $i = 0;
    } 

Upvotes: 1

Related Questions