You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中使用isset函数显示闰年确认消息异常问题排查

闰年计算器代码错误分析与修复

核心错误点

  • $year变量赋值错误
    $year = isset($_GET["leapyear"]); 中isset()返回的是布尔值(存在为true,不存在为false),导致$year实际是布尔类型,输出时会被转换为字符串"1",这就是你看到"1 is a leapyear"的直接原因。正确写法应获取用户输入的实际年份:

    $year = isset($_GET["leapyear"]) ? trim($_GET["leapyear"]) : '';
    
  • 未调用闰年判断函数,判断逻辑完全失效
    当前代码直接用$year == true做判断,完全没用到你定义的is_leapyear函数,逻辑完全偏离需求,必须调用该函数来验证年份是否为闰年。

  • is_leapyear函数逻辑错误
    原函数仅将能被400整除的年份判定为闰年,漏掉了“能被4整除但不能被100整除”的核心闰年规则。正确的闰年判断逻辑需覆盖两种情况:

    1. 能被4整除且不能被100整除;
    2. 能被400整除。

修正后的完整代码

<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Web,programming" />
<title>Leap year form</title>
</head>
<body>
<?php
$year = isset($_GET["leapyear"]) ? trim($_GET["leapyear"]) : '';

function is_leapyear($year){
    if(!is_numeric($year)){
        return false;
    }
    $year = (int)$year;
    // 正确的闰年判断逻辑
    return ($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0);
}

if (isset($_GET["confirm"])){
    if (!empty($year) && is_leapyear($year)){
        echo '<span style="color:#008631;">';
        echo "$year is a leap year</span>";
    }else{
        echo '<span style="color:#FF0000;">';
        echo "$year is not a leap year</span>";
    }
}
?>
<h1>Lab 03 Task 2 - Leap Year</h1> 
<form action = "leapyear_selfcall.php" method = "get" >
    <label for="leapyear">Enter a year</label>
    <input type="text" name="leapyear"/>
    <p>
        <input type="submit" name="confirm" value="Check For Leap Year"/>
    </p>
</form>
</body>
</html>

内容的提问来源于stack exchange,提问作者Bheki Fuzwayo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:35:18