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:

<?php
$hours_array[1]=1;
$hours_array[2]=2;
$hours_array[3]=3;
$hours_array[4]=4;
$hours_array[5]=5;
$hours_array[6]=6;
$hours_array[7]=7;
$hours_array[8]=8;
$hours_array[9]=9;
$hours_array[10]=10;
$hours_array[11]=11;
$hours_array[12]=12;
?>

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 *