RSM
RSM

Reputation: 15108

foreach statement forcing while/for to loop too many times

I have a while/for loop with a foreach loop inside. Reading the code will make it self explanatory as to what I am trying to achieve in terms of logic.

In layman's terms, I am trying to create a calendar in PHP. The foreach statement creates 35 cells, for the calendar interface, 4 weeks, 7 days, 5 x 7 = 35.

The while loop has taken the number of days in April (30) and trying to each the range 1-30 in each cell.

However, when implementing the code below, each number gets iterated 30 times.

$i = 1;
while ($i <= 30){
    foreach ($this->cells as $cells){
        foreach ($cells as $key => $object){
            echo "<td>" . $i . "</td>";                     
            if($object % 7 == 0){
                echo "</tr><tr>";
            }
        }  
    }
    $i++;   
}

I tried this:

$i = 1;
while ($i <= 30){
    foreach ($this->cells as $cells){
        foreach ($cells as $key => $object){
            echo "<td>" . $i . "</td>";  $i++;                              
            if($object % 7 == 0){
                echo "</tr><tr>";
            }
        }  
    }

}

Which instead of outputting 1-30 many times each, it outputs 1-35, when I only want 1-30.

I have tried a for loop with the result it prints many of each number. For loop code:

for ($i = 1; $i <= 30; $i++){
                foreach ($this->cells as $cells){
                    foreach ($cells as $key => $object){
                echo "<td>" . $i . "</td>";             
                if($object % 7 == 0){
                    echo "</tr><tr>";
                }
                    }  
                }   
            }   

$this->cells is a range 1-35 in an array

Upvotes: 2

Views: 362

Answers (2)

billyonecan
billyonecan

Reputation: 20250

$i=0;
while ($i++ < 35){
    echo '<td>' . ($i <= 30 ? $i : '&nbsp;') . '</td>';
    if($i % 7 == 0) {
        echo '</tr><tr>';
    } 
}

I'm not really sure why you need to do two loops, you could do it all with one (unless you do need to loop over $this->cells, in which case ignore this answer :p)

Upvotes: 1

Salil Momin
Salil Momin

Reputation: 361

$i=0;
foreach ($this->cells as $cells){
    foreach ($cells as $key => $object){
        if($i<=30)
            echo "<td>" . $i . "</td>";
        $i++;                              
        if($object % 7 == 0){
            echo "</tr><tr>";
        }
    }
}  

Try this code

Upvotes: 2

Related Questions