How to keep select box value selected using php

02nd, January 2018 By

To Show the option as selected in html you can do this with selected=”selected” but if you want to make it dynamic using php you need to compare every option with particular data on that basis you can show the option as selected.For example:


Here I have used an array of hours it will be used for select box options.

 <?php foreach($hours_array as $key3=>$value3){ ?>
      <option <?php if($value3==3){
           ?> selected="selected"<?php }  ?>>
           <?php  echo $value3; ?> </option> <?php }?>

Here I have used array for options for every option I have compared it with my data when it matches it will show that option as selected here it will show hour number 3 option as selected you can use any variable in place of 3 .

Selectbox value

Here in first selectbox I have not used selected=”selected” it is showing its default value but the others are showing the selected option based on the match.

Leave a Reply

Your email address will not be published. Required fields are marked *