1

簡単なプロジェクトに取り組み、その目的はうるう年かどうかを調べることです。PHP では、標準の elseif ステートメントではなく 3 項を使用しようとしました。

$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));

true私の質問は、三項演算子が上部またはfalse分岐に括弧を必要とするのはなぜですか? 上記のコードはあいまいではないと思います。

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 に答える