从今年开始以相反的顺序打印年份到PHP的最后10年

时间:2016-06-06 10:05:42

标签: php

我试图从今年(2016年)开始以相反的顺序印刷年份,例如:

2016
2015
2014
..
2006

为此我使用'for'循环:

$year1 = date("Y");
$endyear = date("Y")-10;
for ($year = $year1; $year < $endyear; $year--) {
    echo "The year is: $year <br>";
}

但它没有显示任何输出。即使我使用相同的代码来增加10年的年份,比如

$year1 = date("Y");
$endyear = date("Y")+10;
for ($year = $year1; $year < $endyear; $year++) {
    echo "The year is: $year <br>";
}

其输出是;

The year is: 2016
The year is: 2017
The year is: 2018
The year is: 2019
The year is: 2020
The year is: 2021
The year is: 2022
The year is: 2023
The year is: 2024
The year is: 2025

我的代码中出现了错误。请帮我按相反的顺序实现这一点。

4 个答案:

答案 0 :(得分:2)

for循环中的条件错误。根据你的问题,这是正确的代码:

<?php

$year1 = date("Y");
$endyear = date("Y")-10;
for ($year = $year1; $year >= $endyear; $year--) {
    echo "The year is: $year <br>";
}

?>

答案 1 :(得分:1)

您需要做的就是翻转<

$year1 = date("Y");
$endyear = date("Y")-10;
for ($year = $year1; $year > $endyear; $year--) {
    echo "The year is: $year <br>";
}

答案 2 :(得分:1)

不是$year < $endyear
但是:$ year&gt; $ endyear

这样:

$year1 = date("Y");
$endyear = date("Y")-10;
for ($year = $year1; $year > $endyear; $year--) {
    echo "The year is: $year <br>";
}

答案 3 :(得分:1)

试试这个: -

$years = range(date("Y")+9,date("Y")); // range(2025,2016)
foreach($years as $year){
  echo "The year is: $year <br>";
}