Working on a simple project, the objective is to find whether or not it is a leap year. In PHP, I attempted to use a ternary rather then the standard elseif statements.
$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';
I discovered that this doesn't work because of a lack of parenthesis. Here is the correct solution:
$is_leapYear = ($year % 400 == 0)? true: (($year % 100 == 0)? false: ($year%4 == 0));
My question is why do ternary operators need parenthesis on the top true
or false
branch? I don't think the above code is ambiguous.