Here is the function I'm not understanding:
$year = date("Y");
$leapYear = false;
if((($year%4==0) && ($year%100==0)) || ($year%400==0))
$leapYear = true;
Does that mean that, if the (($year is divided by 4 but not divided by 100) or (the year is divided by 400))
that is a leap year?
I'm new to PHP, please anyone help me to understand the statements.
This is basically what is says in pseudo code
if(year is divisible by 4 or 100) {
leapyear = true
} else if (year is divisible by 400) {
//this will never be hit because it would meet the first case
leapyear = true
}
Based on your code, your second guess is correct.
if((($year % 4==0) && ($year % 100==0)) || ($year % 400==0))
means that EITHER of these must be true to be a leap year:
($year%4==0) && ($year%100==0)
$year%400==0
So a year is a leap year under these conditions:
OR
However, the code you posted is wrong in that it doesn't correctly define a leap year.
A year is a leap year if it is divisible by 4, except when it is divisible by 100 and not divisible by 400. So in your if
statement the ($year % 100 == 0)
should be ($year % 100 != 0)
So the proper logic would be this:
if ((($year % 4 == 0) && ($year % 100 != 0)) || ($year % 400 == 0))
$leapYear = true;
&&
:&&
means AND, and the expression A && B
is either true or false.
By definition, A && B
is true only if both A
and B
are true. If any of them are false, then A && B
is false.
I think you're likely confused because the code you've provided doesn't find leap years. Leap years are divisible by 4 but NOT 100.. unless they are also divisible by 400. If you flip the logic around, it's easier to look at. If it's divisible by 400, it's a leap year, no matter what. Otherwise, it's a leap year if it's divisible by 4 and NOT divisible by 100.
// pseudocode
if ( year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
return true;
else
return false;
You can play around with it and just say:
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
The && means both sides have to be true
in order for && to return true
.