Search code examples
phphtml-selectselectedvalue

How to make selected in the year option with php?


I want to make the selected in the year option with PHP, but my coding is not working. For example, if I want the selected year is 2019, then the option will show 2019 selected at first. Hope someone can guide me on which part I am getting wrong. Thanks.

Below is my coding:

<select id="year" class="form-control" name="year" title="Year">
    <option value="">Please Select</option>

<?php
$result_arr_['year'] = "2019";
if($result_arr_['year'] == true){
    $selected_year = "selected";
}else{
    $selected_year = " ";
}

for ($year = (int)date('Y'); 1900 <= $year; $year--): ?>
    <option value="<?=$year;?>" <?php echo $selected_year;?>><?=$year;?></option>
<?php endfor; ?>
</select>   

My output just show me start with the 1900 year, not 2019.

output


Solution

  • you need to test each date generated by the loop, inside the loop

    <select id="year" class="form-control" name="year" title="Year">
        <option value="">Please Select</option>
    
    <?php
    $result_arr_['year'] = "2019";
    
    for ($year = (int)date('Y'); 1900 <= $year; $year--): 
        $selected = $result_arr_['year'] == $year ? " selected='selected' " : '';
    ?>
        <option value="<?=$year;?>" <?= $selected;?>><?=$year;?></option>
    <?php
    endfor;
    ?>
    </select>