1

在一个简单的项目上工作,目标是确定它是否是闰年。在 PHP 中,我尝试使用三元而不是标准的 elseif 语句。

$year = 2000;
$is_leapYear = ($year%400 == 0)? true: ($year%100 == 0)? false: ($year % 4 == 0);
echo ($year % 400 == 0) .'.'. ($year % 100 == 0) .'.'. ($year % 4 ==0);
echo $year . ' is ' . ($is_leapYear ? '' : 'not') . ' a leap year';

我发现这不起作用,因为缺少括号。这是正确的解决方案:

$is_leapYear = ($year % 400 == 0)? true: (($year % 100 == 0)? false: ($year%4 == 0));

我的问题是为什么三元运算符需要在顶部truefalse分支上加括号?我不认为上面的代码是模棱两可的。

4

2 回答 2

3

不需要这么复杂的代码。PHP 的 date() 可以返回是否是闰年:

$is_leap_year = (bool) date('L', mktime(0, 0, 0, 1, 1, $year));

请参阅此处的手册

于 2013-02-12T18:04:20.873 回答
2

PHP三元运算符没有歧义和悲伤:

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?> 

来源

您的代码执行如下:

$year = 2000;
$is_leapYear = (($year%400 == 0)? true: ($year%100 == 0)) ? false: ($year%4==0);
echo $is_leapYear;

左到右

于 2013-02-12T18:10:14.960 回答