1

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>
Taylor Jeff
  • 27
  • 1
  • 1
  • 7
  • Sort the PHP array before your code above. Search on "php sort" for examples. – Dave S Feb 24 '18 at 00:21
  • Possible duplicate of [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – Tobias Xy Feb 24 '18 at 00:22
  • 3
    You really don't need to sort on PHP, just specify ORDER BY when you get cities from database. – Triby Feb 24 '18 at 00:24

2 Answers2

4
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

ezw
  • 338
  • 2
  • 12
  • worked like a charm. I suppose I could have used order by, but I wasn't sure of the syntax given the array ($city_list as $city). – Taylor Jeff Feb 24 '18 at 01:12
1

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.

Christian Hur
  • 429
  • 3
  • 10
  • I get that. Got to your answer after approving the sort one. This is such a tiny little web page so speed is not an issue, but point taken. – Taylor Jeff Feb 24 '18 at 01:13
  • The sort() function may apply for any array, not just an array from DB, so the sort() answer is the correct for this question – Aberel Feb 24 '18 at 01:46