含糊不清的三元陈述

时间:2013-02-12 18:00:03

标签: php

在一个简单的项目上工作,目标是找出它是否是闰年。在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分支上使用括号?我不认为上面的代码含糊不清。

2 个答案:

答案 0 :(得分:3)

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

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

请参阅manual here

答案 1 :(得分: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.
?> 

SOURCE

您的代码执行如下:

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

左到右