How to display select option of <select> tag as selected in 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.

Method 1 : Simple html select tag to display option as selected in html.

You just need to add an attribute  “selected” to the option that you want to be selected. In the below code (Method 1)  option samsung with value 2 has been selected. 

<!-- Method 1 -->

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

 

Method 2 :   Display option as selected in php using GET method.

<!-- Method 2 -->
<select name="up_opt">
    <option value="1" <?php if ($_GET['up_opt'] == 1) { echo ' selected="selected"'; } ?>>Opt1</option>
    <option value="2" <?php if ($_GET['up_opt'] == 2) { echo ' selected="selected"'; } ?>>Opt2</option>
    <option value="3" <?php if ($_GET['up_opt'] == 3) { echo ' selected="selected"'; } ?>>Opt3</option>
</select>

If you are getting any error while executing above code (Method 2) pass query string (URL parameters) in your address bar as ?up_opt=3

 

Method 3 :   Display selecet option as selected in php using foreach method with if  statement.

<!-- Method 3 -->
<select name="country" id="country">
  <option value="" selected="selected">Please Choose</option>
    <?php
    foreach($countries as $key => $val){
    ?>
      <option value="<?= $key; ?>" <?php if ($val == 'CAMEROON') { echo ' selected="selected"'; } ?>> <?= $val ?> </option>
    <?php
    }
    ?>
</select>

 

Method 4 :   Display selecet option as selected in php using foreach method with ternary operator.

Create an array and  iterate it in a foreach loop and make a condition where value of an array is equal to the option value of select for which option  you want to be selected. Here the value CAMEROON is used to selected the particular option. You can change or pass dynamic value as per your requirments.

 

<!-- Method 4 -->
<?php  
    $countries = array(
    'AF'=>'AFGHANISTAN',
    'BS'=>'BAHAMAS',
    'KH'=>'CAMBODIA',
    'CM'=>'CAMEROON',
    'KY'=>'CAYMAN ISLANDS',
    'TD'=>'CHAD',
    'CL'=>'CHILE',
    'KM'=>'COMOROS',
    'CG'=>'CONGO',
  );

   ?>

<select name="country" id="country">
  <option value="" selected="selected">Please Choose</option>
  <?php 
     foreach($countries as $key => $val){
         $selected = ($val == 'CAMEROON') ? 'selected="selected"' : '';
          echo '<option value="'. $val .'" ' . $selected . ' >'. $key .'</option>';
     }
   ?>
</select>