Owen
Owen

Reputation: 431

Loops in PHP to repeat incrementing value over array

I am having an issue where I create a loop of headings. I want to create a list of dates for each heading, these dates are pulled from MySQL as are the headings.

I think I am looking to loop within an loop.

I think once $h reaches $number_of_days it doesn’t reset even though it is within the 1st while loop. Is there a different way to go about this?

$h='1';
          while($report_types = $rt_type->fetch())
            {


$rt_types = $report_types['report_name'];
            echo '<div>'. $rt_types .'</div>';


while($h <= $number_of_days){          
            echo '<div class="report_day">'.$h.'</div>';
            $h++;

            }    
        }

Upvotes: 0

Views: 65

Answers (3)

nl-x
nl-x

Reputation: 11832

Put $h='1'; inside the first while.

So change:

$h='1';
while($report_types = $rt_type->fetch())
{

into:

while($report_types = $rt_type->fetch())
{
    $h='1';

Upvotes: 0

Giacomo1968
Giacomo1968

Reputation: 26066

Part of problem with your code is coming from formatting more than anything. The less readable code is, the harder it is to debug.

That said, here is my reworked version of your code:

while($report_types = $rt_type->fetch()) {
  $rt_types = $report_types['report_name'];
  echo '<div>' . $rt_types . '</div>';
  for ($h = 1; $h <= $number_of_days; $h++) {
    echo '<div class="report_day">' . $h . '</div>';
  }
}

What I did is remove the while loop & switched it to for loop which makes the logic a bit cleaner. So now your $h1 incrementing logic is all contained in this one line for ($h = 1; $h <= $number_of_days; $h++) { which makes it all easier to read & understand as well.

Also, as far as your original code goes, this assignment to $h is problematic:

$h='1';

When you place a value in quotes like that it makes the contents within those quotes a literal string. For numerical purposes like this you would set that as:

$h=1;

Upvotes: 0

Biotox
Biotox

Reputation: 1601

I added a reset to $h before the next loop of $report_types

    $h=1;
    while($report_types = $rt_type->fetch())
    {
        $rt_types = $report_types['report_name'];
        echo '<div>'. $rt_types .'</div>';


        while($h <= $number_of_days){          
            echo '<div class="report_day">'.$h.'</div>';
            $h++;
        }

        $h=1; //RESET BEFORE NEXT LOOP
    }

Upvotes: 3

Related Questions