Search code examples
phploopsiterationnonsequential

PHP Loop - dealing with non-sequential iterations


I have the following code - it produces a series of queries that are sent to a database:

$a = 'q';
$aa = 1;
$r = "$a$aa";
$q = 54;

while($aa <= $q){
$query  .= "SELECT COUNT(". $r .") as Responses FROM tresults;";
$aa = $aa + 1;
$r = "$a$aa";
}

The issue I have is simple, within the database, the number is not sequential.

I have fields that go from q1 to q13 but then goes q14a, q14b, q14c, q14d and q14e and then from q15 to q54.

I've looked at continue but that's more for skipping iterations and hasn't helped me.

I'm struggling to adapt the above code to handle this non-sequential situation. Any ideas and suggestions welcomed.


Solution

  • I have fields that go from q1 to q13 but then goes q14a, q14b, q14c, q14d and q14e and then from q15 to q54.

    for($i=1; $i<=54; ++$i) {
      if($i != 14) {
        echo 'q' . $i . "<br>";
      }
      else {
        for($j='a'; $j<='e'; ++$j) {
          echo 'q14' . $j . "<br>";
        }
      }
    }
    

    If you don’t need to execute the statements in order of numbering, then you could also just skip one in the first loop if the counter is 14, and then have a second loop (not nested into the first one), that does the q14s afterwards.