Skip to content


How to set the selected option of <select> tag from the PHP

There is a few ways to do this. The easiest way to do this is in fact really simple, you just need to add a keyword “selected” to the option that you want selected.
For example, if You have something like this:

1
2
3
4
5
<select>
   <option value="1">Apple</option>
   <option value="2">Samsung</option>
   <option value="3">HTC</option>
</select>


If we want to have “Samsung” selected:

1
2
3
4
5
<select>
   <option value="1">Apple</option>
   <option selected value="2">Samsung</option>
   <option value="3">HTC</option>
</select>

Pretty easy, don’t you thing so :)

Now next thing that we need to do is to make our <select> submit so we could arrange the page accordingly.
To do that, we need to put it inside a <form>, like this:

1
2
3
4
5
6
7
<form>
   <select id="company" name="company"> 
      <option value="1">Apple</option> 
      <option value="2">Samsung</option> 
      <option value="3">HTC</option> 
   </select> 
</form>

Depending on your needs and requirements you may need some extra parameters set to the <form> tag, but for our example this is just fine
You can notice I added “id” and a “name” to the <select> tag, we will you these names to access the value at the backend.

Now for the fun part, let’s add some basic PHP code and bring our example to life.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
 
(isset($_POST["company"])) ? $company = $_POST["company"] : $company=1;
 
?>
 
<form>
<select id="company" name="company">
<option <?php if ($company == 1 ) echo 'selected'; ?> value="1">Apple</option>
<option <?php if ($company == 1 ) echo 'selected'; ?> value="2">Samsung</option>
<option <?php if ($company == 1 ) echo 'selected'; ?> value="3">HTC</option>
</select>
</form>

And that’s it. It has no real use, but it is good to get a grip of how the things work.

Hope someone finds this useful, and also that someone can contribute and make the examples better.

Posted in PHP.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.