PHP List of Countries

Hi,

I have a fully working drop-down list of countries that are pulled from a countries table within the database, but what I would like to do is display the UK, France and Monaco first before the rest of the countries. How would I go about doing this?

Regards.

Hard code them?

You could create another column in your Countries table called something like “SortOrder” and put UK, France, Monaco = (1,2,3) and all the rest as 4+. Then in your query order by SortOrder

Yes, you should hard code them in at the top of the select statement. It’s okay to have them listed twice, in fact it’s even better.

The best way would be to have your countries ordered in your database table with an order column. Then use the order column to order them alphabetically except for the ones you want at the top. Then when you run your query, order by the order column. Edit: I see BrandonE already said that now… I’m just a slow typer.

If this is a simple and small project without serious performance needs, here’s another way you could do it (this is untested prototype code off the top of my head, assuming your countries are already html friendly and string safe):

$result = mysql_query($query);
$firstCountries = array('UK', 'France', 'Monaco');

// print first countries
foreach($firstCountries as $c)
  print "<option value=\\"$c\\">$c</option>\
";

// print all countries in the query, excluding the first countries
while($row = mysql_fetch_row($result))
{
  $c = $row[0];
  if(!in_array($c, $firstCountries))
    print "<option value=\\"$c\\">$c</option>\
";
}

But you should really ask yourself if removing the countries from the list and adding them to the top of the list is the right thing to do. Although, it seems logical it actually isn’t such a great design.

What you really want are just shortcuts, so just hard-code the shortcuts and then list the full list below the shortcuts. This is in-case any 1 person skips the shortcuts and searches the list for his country and gets terrible annoyed that he can’t find it. Never under estimate your end user, make things as easy as possible.

Thanks guys - I simply hard coded in the ID and name to the drop down box, would ideally like it dynamic (will try your ideas Brandon/smallshot eventually) but it will do for now.

Thanks again.

what do you mean dynamic?

<select ..>
<option ...>UK</option>
<option ...>France</option>
<option ...>Monoco</option>
<?php
while($row = mysql_fetch_row($result))
{
 //Loop out countries in order
}?>
</select>

The order would show as uk, France, Monoco, Algeria…