title: how can i get a php variable outside a while loop which is in a function
body: <pre><code>function getTowns($conn)
  {
      $sql = "SELECT towns.name, towns.id, regions.name AS region_name FROM towns INNER JOIN regions ON towns.region_id = regions.id ORDER BY name ASC";
      $result = $conn-&gt;query($sql);
      $town_opt = ''; //stands for town option
  
      town_opt .= "&lt;datalist id='townlist'&gt;";
      while ($row = $result-&gt;fetch_assoc()) {
          $town_id = $row['id'];
          $town_opt .= "&lt;option&gt;" . $row['name'] . ", " . $row['region_name'] .  "&lt;/option&gt;";
      }
  
      $town_opt .= "&lt;/datalist&gt;";
      return $town_opt;
  };
  
  echo $town_id;
  echo getTowns($conn);
  //how can I echo every town id? 
  </code></pre>
  
  <p>This is the best I could think of, and yet it doesn't work. I tried setting a cookie but it still wasn't working the way I wanted.</p>