PHP - 在选择框中设置默认年份

问题描述 投票:0回答:1

我被指示创建一个选择框,允许用户选择当年的年份 - 5到2050年。默认年份必须是当前年份。目前该列表从2014年开始(当前年份-5)。

我将默认年份显示设置为2019而不是2014.我们假设使用DateTime对象和与DateTime类一起使用的格式。

我包括我也为选择框编写的代码,允许用户选择一个月。如果适合提问,我也会很感激对此的反馈。我还必须创建一个允许用户选择整年的复选框。我创建了复选框,但不知道如何开始编码以选择整年。

编辑添加:此分配必须仅使用PHP和HTML以及一些CSS样式。

<section>
    <form id="yearForm" name="yearForm" method="post" action="">
        <label for="select_year">Select the year: </label>
        <?php
        // Sets the default year to be the current year.
        $current_year = date('Y');
        // Year to start available options.
        $earliest_year = ($current_year - 5);
        // Set your latest year you want in the range.
        $latest_year = 2050;

        echo '<select>';
        // Loops over each int[year] from current year, back to the $earliest_year [1950]
        foreach ( range( $earliest_year, $latest_year ) as $i ) {
            // Echos the option with the next year in range.
            echo '<option value="'.$i.'" '.($i === $current_year ? ' selected="selected"' : '').'>'.$i.'</option>';
        }
        echo '</select>';
        ?>
    </form>
        <br />
        <br />
    <form id="monthForm" name="monthForm" method="post" action="">
        <label for="month">Select the month: </label>
<!--        <input type=hidden id="month" name=month>-->
                        <select id="month" name="month" >
                            <option value='01'>January</option>
                            <option value='02'>February</option>
                            <option value='03'>March</option>
                            <option value='04'>April</option>
                            <option value='05'>May</option>
                            <option value='06'>June</option>
                            <option value='07'>July</option>
                            <option value='08'>August</option>
                            <option value='09'>September</option>
                            <option value='10'>October</option>
                            <option value='11'>November</option>
                            <option value='12'>December</option>
                        </select>
                        <br />
                        <br />
        <label for="whole_year">Show whole year: </label>
        <input type="checkbox" id="whole_year" name="whole_year" >
        <br />
        <br />
        <input type="submit" class=inline name="submitButton" id="submitButton" value="Submit" />
    </form>
php
1个回答
3
投票

$i是一个整数,$current_year是一个字符串所以严格比较,===,这些不匹配。使用==进行比较,它应该有效。

($i == $current_year ? ' selected="selected"' : '')

https://3v4l.org/k1P7T

有关这方面的更多信息,请参阅http://php.net/manual/en/language.operators.comparison.php

如果将数字与字符串进行比较或比较涉及数字字符串,则每个字符串将转换为数字,并且数字执行比较。这些规则也适用于switch语句。当比较为===或!==时,不会发生类型转换,因为这涉及比较类型和值。

© www.soinside.com 2019 - 2024. All rights reserved.