0

I have a database field country which I want to query and select that country option from a select element. Is there any way to do this without adding:

if (query->country == "<some country>"){echo "selected"} 

in every single option tag? As there are hundreds of country options. Here is a little example of the code. Thank you.

$query = $query->fetch_object();

// which ever country is held in the variable `$query->country` should be selected

echo"<select>
       <option>Afghanistan</option>
       ......
       ......
       <option>Zimbabwe</option>
     </select>"; 
1
  • You can do it easily if you've an array of countries. Simply match the value and echo when it matches. Commented Aug 3, 2014 at 16:59

2 Answers 2

1

Don't you have a list of all countries on your server?

$countries = ["Afghanistan", ... , "Zimbabwe"];

You could do something like this:

$selection = "Some country";

echo "<select>";

foreach($countries as $country)
{
    if($country == $selection)
        echo "<option selected>" . $country . "</option>";
    else
        echo "<option>" . $country . "</option>";
}

echo "</select>";
Sign up to request clarification or add additional context in comments.

1 Comment

I will use this method. I just have to make one mammoth of a country array:).Thanks for the answer.
1

The IF still needs to be "placed" on every <option> but as a programmer you should do something like this:

$options = array( 'Afghanistan', '...', 'Zimbabwe' );

foreach( $options as $option )
{
    $selected = ( $query->country == $option )? ' selected': '';
    echo '<option' . $selected . '>' . $option . '</option>';
}

and if you're unfamiliar with ternary operator, the $selected = ... part above can be written like this:

if ( $query->country == $option )
{
    $selected = ' selected';
}
else
{
    $selected = '';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.