我需要计算从下拉列表 PHP 中选择的两年之间的人口差异?

I need to do a calculation of the population difference between two years chosen from drop down list PHP?

所以我有 2 个下拉列表,我需要从中选择年份。然后我需要显示所选年份和那一年的人口数量。 例如:

1800 年:人口为:3,929,214
1900 年:人口为:76,212,168
人口增加:72,282,954.

到目前为止,这是我的代码:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Calculator</title>
    </head>
    <body>
        <h1>Population Change Calculator</h1>
        <?php
        $population=[3929214,5236631,7239881,9638453,12866020,17069453,23191876,31443321];
        $year=(range(1790, 1860, 10));
        $array= array_combine($year, $population);
        ?>
        <form method="post">
            <p><label for="year1">Year 1:</label>
                <select name="year1">
                    <option value=""></option>
                    <?php
                        foreach ($array as $year1=>$population){ ?>
                    <option value="<?php echo $year1; ?>"><?php echo $year1; ?></option>       
                    <?php    }
                    ?>
                </select>
            </p>
            <p>
                <label for="year2">Year 2:</label>
                <select name="year2">
                    <option value=""></option>
                    <?php
                        foreach ($array as $year2=>$population){ ?>
                    <option value="<?php echo $year2; ?>"><?php echo $year2; ?></option>       
                    <?php    }
                    ?>
                </select>
            </p>
            <input type="submit" name="submit" value="Submit">
            <br>

        </form>
        <?php
        $ini_set = ini_set('display_errors', 1);
    error_reporting(E_ALL);

        $empty=true;
        if(isset($_POST['submit'])){
            if(empty($_POST['year1'])){
                $empty=FALSE;
                print "<p>Please choose Year 1.</p>";
            }

            if(empty($_POST['year2'])){
                $empty=false;
                print "<p>Please choose Year 2.</p>";
            } 
}

我不知道如何打印所选年份和那一年的人口。
我是 PHP 的新手,在此先感谢您。

您将 'year' 选项的值设置为人口似乎很奇怪。也许这是一个错误..?

您应该将它们更改为使用年份:

<option value="<?php echo $year1; ?>"><?php echo $year1; ?></option>

完成后,您可以通过执行以下操作打印所需的值:

if (isset($_POST['submit'])) {
    if (empty($_POST['year1'])) {
        $empty = FALSE;
        print "<p>Please choose Year 1.</p>";
    } else {
        print "<h1>Year 1: {$_POST['year1']}</h1>";
        print "<p>Population: {$array[$_POST['year1']]}</p>";
    }

    if (empty($_POST['year2'])) {
        $empty = false;
        print "<p>Please choose Year 2.</p>";
    } else {
        print "<h1>Year 2: {$_POST['year2']}</h1>";
        print "<p>Population: {$array[$_POST['year2']]}</p>";
    }
}