Taylor Jeff
Taylor Jeff

Reputation: 27

How to sort a php foreach loop in an html form

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

Answers (2)

Christian Hur
Christian Hur

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

ezw
ezw

Reputation: 430

City:
<select name="city">
<option value="" selected="selected">Any</option>
<?php
sort($city_list);   // <-- The magic
foreach($city_list as $city) : ?>
<option><?php echo $city; ?></option>
<?php endforeach; ?>
</select>

sort

Upvotes: 4

Related Questions