title: Is there a more efficient way of writing a select list grouped by state in php
body: <p>I am building a website and it has a select list grouped by state. Is there a more effective way of writing this select list, so I don't have a write so many different for loops? </p>
  
  <p>I have a table in my database called location:</p>
  
  <pre><code>id    region            state
  1     Sydney            NSW
  2     Newcastle         NSW
  3     Wollongong        NSW
  4     Wagga Wagga       NSW
  5     Geelong           Vic
  </code></pre>
  
  <p>...etc</p>
  
  <p>Currently I am printing them out in a select list grouped by state like this. </p>
  
  <pre><code>&lt;select name="location" id="location"&gt;
      &lt;?php 
          $locations = getTable("location", $DB); 
          $locationsByState = [];
          //chunk array by state
          foreach($locations as $loc)
          {
              $locationsByState[$loc['state']][] = $loc;
          }
      ?&gt;
      &lt;optgroup label="NSW"&gt;
          &lt;?php
              foreach($locationsByState['NSW'] as $opt)
              echo '&lt;option&gt;' . $opt['region'] .'&lt;/option&gt;'
          ?&gt;
      &lt;/optgroup&gt;
      &lt;optgroup label="QLD"&gt;
          &lt;?php
              foreach($locationsByState['QLD'] as $opt)
              echo '&lt;option&gt;' . $opt['region'] .'&lt;/option&gt;'
          ?&gt;
      &lt;/optgroup&gt;
      &lt;optgroup label="SA"&gt;
          &lt;?php
              foreach($locationsByState['SA'] as $opt)
              echo '&lt;option&gt;' . $opt['region'] .'&lt;/option&gt;'
          ?&gt;
      &lt;/optgroup&gt;
      &lt;optgroup label="VIC"&gt;
          &lt;?php
              foreach($locationsByState['VIC'] as $opt)
              echo '&lt;option&gt;' . $opt['region'] .'&lt;/option&gt;'
          ?&gt;
      &lt;/optgroup&gt;
      &lt;optgroup label="TAS"&gt;
          &lt;?php
              foreach($locationsByState['TAS'] as $opt)
              echo '&lt;option&gt;' . $opt['region'] .'&lt;/option&gt;'
          ?&gt;
      &lt;/optgroup&gt;
      &lt;optgroup label="WA"&gt;
          &lt;?php
              foreach($locationsByState['WA'] as $opt)
              echo '&lt;option&gt;' . $opt['region'] .'&lt;/option&gt;'
          ?&gt;
      &lt;/optgroup&gt;
      &lt;optgroup label="ACT"&gt;
          &lt;?php
              foreach($locationsByState['ACT'] as $opt)
              echo '&lt;option&gt;' . $opt['region'] .'&lt;/option&gt;'
          ?&gt;
      &lt;/optgroup&gt;
      &lt;optgroup label="NT"&gt;
          &lt;?php
              foreach($locationsByState['NT'] as $opt)
              echo '&lt;option&gt;' . $opt['region'] .'&lt;/option&gt;'
          ?&gt;
      &lt;/optgroup&gt;
  &lt;/select&gt;
  </code></pre>