Dr. Ske
Dr. Ske

Reputation: 69

How to set default option for <select> based on PHP variable (POST / GET / SESSION etc.)

I am using HTML + PHP to build a web App.

I wanted to create an editable form that includes a couple of <select> fields. As an example, we can assume that I want to create a user profile.

The thing is, when new user wants to edit some data about himself, all fields are empty. For the field sex it may look like this:

<select class="form-select" name="sex" required>
    <option value="">-</option>
    <option value="M">Male</option>
    <option value="F">Female</option>
</select>

or:

<select class="form-select" name="sex" required>
    <option selected value="">-</option>
    <option value="M">Male</option>
    <option value="F">Female</option>
</select>

Whereby default the empty value described by "-" will be displayed.

But what about when the user already has filled that field? Let's assume we have an object variable $user and may access his/hers sex by $user->sex. By default, I want the <select> to be selected with the proper attribute. Using PHP I may go for something like this:

<select class="form-select" name="sex" required>
    <?php if ($user->sex == 'M') : ?>
        <option value="">-</option>
        <option selected value="M">Male</option>
        <option value="F">Female</option>
    <?php elseif($user->sex == 'F' : ?>
        <option value="">-</option>
        <option value="M">Male</option>
        <option selected value="F">Female</option>
    <?php else : ?>
        <option selected value="">-</option>
        <option value="M">Male</option>
        <option value="F">Female</option>
    <?php endif; ?>
</select>

But that requires a lot of if, elseif statements. As an example, I've provided only three-optional field. What about when there are more options?

Is there any elegant solution to choose a selected option of <select>, based on a variable (object fetched from database / POST / GET / SESSION - does not really matter), without using so many ifs? At best, I'd like to list possible options only once and then tell the site which is to be chosen by default.

Thanks everyone in advance!

Upvotes: 0

Views: 1045

Answers (1)

Suboptimierer
Suboptimierer

Reputation: 614

Why do you repeat the options? Just check every option if it needs to be selected...

<select class="form-select" name="sex" required>
    <option <?php if($user->sex == "") echo "selected" ?> value="">-</option>
    <option <?php if($user->sex == "M") echo "selected" ?> value="M">Male</option>
    <option <?php if($user->sex == "F") echo "selected" ?> value="F">Female</option>
</select>

Upvotes: 1

Related Questions