title: PHP alternative to loop inside a HEREDOC
body: <p>I am trying to create loop inside of a HEREDOC in php. I know that it is not possible to do so, but it was the best way for me to tell what I need help for..
  This is my code:</p>
  
  <pre><code>&lt;?
  $sth = $dbh-&gt;prepare("SELECT field1, field2 FROM table WHERE id = '".$_GET['id']."'");
  $sth-&gt;execute();
  echo &lt;&lt;&lt;HERE_DOC
      [
      while($row = $sth-&gt;fetch()){ 
          echo '{"optionValue":"'.$row['field1'].'", "optionDisplay": "'.$row['field2'].'"},'; 
      }
      ]
  HERE_DOC;
  ?&gt;
  </code></pre>
  
  <p>and it tells me this</p>
  
  <pre><code> Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /public_html/test.php on line 7
  </code></pre>
  
  <p>I think it returns this because it is not possible to create a loop inside a HEREDOC - but how do I do this otherwise..?</p>
  
  <p>The script is driving by AJAX with this script:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  $(function(){
    $("select#state").change(function(){
      $.getJSON("test.php",{id: $(this).val(), ajax: 'true'}, function(j){
        var options = '';
        for (var i = 0; i &lt; j.length; i++) {
          options += '&lt;option value="' + j[i].optionValue + '"&gt;' + j[i].optionDisplay + '&lt;/option&gt;';
        }
        $("select#city").html(options);
      })
    })
  })
  &lt;/script&gt;
  </code></pre>
  
  <p>and the original test.php is like this:</p>
  
  <pre><code>if ($_GET['id'] == "1234") {
    echo &lt;&lt;&lt;HERE_DOC
      [
      {"optionValue":"000", "optionDisplay": "a"},
      {"optionValue":"300", "optionDisplay": "s"},
      {"optionValue":"600", "optionDisplay": "d"},
      {"optionValue":"700", "optionDisplay": "cr"},
      {"optionValue":"500", "optionDisplay": "Gı"},
      {"optionValue":"400", "optionDisplay": "K"},
      {"optionValue":"800", "optionDisplay": "S"},
      {"optionValue":"900", "optionDisplay": "ik"},
      {"optionValue":"350", "optionDisplay": "Tu"}
      ]
  HERE_DOC;
  else if ($_GET['id'] == "2345") { etc......
  </code></pre>
  
  <p>The thing is that I already have all the data in an SQL database, and I would like to just return the data based on the id from previous select list since there is a lot of options.</p>