Reputation: 27
I have a form that allows users to select from a list of cities in options. I use a foreach() approach to automatically populate the options with all cities in the database, The problem is that I am not sure how to get the results to sort alphabetically.
Here is the code so far without any sorting:
City:
<select name="city">
<option value="" selected="selected">Any</option>
<?php foreach($city_list as $city) : ?>
<option><?php echo $city; ?></option>
<?php endforeach; ?>
</select>
Upvotes: 1
Views: 11432
Reputation: 429
Best way is to sort the result set via the SQL query as Triby suggests.
For example:
$query = "SELECT city FROM CityTable ORDER BY city ASC";
It's much more efficient and quicker by leveraging the power of database server to do the job. That's what db servers are built to do.
Upvotes: 1