KANAYO AUSTIN KANE KANAYO AUSTIN KANE - 5 months ago 8
PHP Question

How to sort a select option according to user input

Please I don't have any idea on how to achieve this so I need help. I have this code:

<select>
<option>Sunday</option>
<option>Monday</option>
/* this option goes down to Saturday */
</select>


And the user have to choose an option which is inserted into the database, let's assume the user chooses Tuesday and wants to edit it later on. Now I want the option that will be visible to be Tuesday eg:

<select>
<option>Sunday</option>
<option>Monday</option>
<option>Tuesday</option> /* this option will be the visible option before the user opens the selection */
</select>


And I want to achieve this through PHP and the variable assigned to the outputted database info is
$day
so
$day = 'Tuesday';
please how do I achieve this?

Answer

To do this from within PHP you could do

<select>
    <option <?PHP echo $day=='Sunday' ? '"selected=selected"' : ''); ?>>Sunday</option> 
    <option <?PHP echo $day=='Monday' ? '"selected=selected"' : ''); ?>>Monday</option> 
    <option <?PHP echo $day=='Tuesday' ? '"selected=selected"' : ''); ?>>Tuesday</option> 

...

</select>

But it is not very elegant and gets difficult to code and more importantly maintain if the selection were to contain more that the seven days of the week.

So using an array of day names and a foreach loop and your $day variable containing the user selected day.

<?php
$dow = array('Sunday','Monday','Tuesday','Wednesday',
             'Thursday','Friday','Saturday');
?>
<select name="DayOfWeek">

<?php
    foreach ( $dow as $d ) :
        $sel = $d == $day ? 'selected="selected"' : '';
        echo "<option $sel>$d</option>";
    endforeach;
?>
</select>
Comments