enter image description here

There is a page with a form where the user enters a date. When you click on the button, the required data is calculated, but the form is reset. That is, the first select option values ​​are again displayed in the form. It is necessary that in the user-selected option of steel with the selected attribute, after clicking on the button, they are again shown in the form. I do this:

<option value="05" <?php if ($_POST["days"] == 5) {echo "selected";} ?>>5</option> <option value="06" <?php if ($_POST["days"] == 6) {echo "selected";} ?>>6</option> 

but too many lines, is there another way?

    3 answers 3

    How about outputting all these lines in a loop?

     <? for ($i = 1; $i<=31; $i++) { ?><option value="<?=$i?>"<? if ($_POST["days"] === $i) { ?> selected<? } ?>><?=$i?></option><? } ?> 

      You can cut it like this:

       <option value="05" <?= $_POST["days"] == 5 ? "selected" : "" ?>>5</option> 

      Ideally, there should be a “widget” that would accept an array of all the elements, and some of which would have the selected code. For example:

       $elements = [ ['value' => '05', 'selected' => false], ['value' => '06', 'selected' => true] ]; <?= Widget::dropDownList($elements);?> 

      Then the Widget::dropDownList should output the select tag.

        You can adapt such a scheme for your task. Only in your case, list through foreach

         $selected[$show]=' selected="selected"'; echo '<select name="show">'."\n"; echo '<option value="1"'.$selected['1'].'>Активен</option>'."\n"; echo '<option value="0"'.$selected['0'].'>Не активен</option>'."\n"; echo '</select>'."\n"; unset($selected);