PHP Program to Check Leap Year with Output and Explanation
if (($year % 400 == 0) || (($year % 4 == 0) && ($year % 100 != 0))) to test the year and print the result.Examples
How to Think About It
Algorithm
Code
<?php $year = 2024; if (($year % 400 == 0) || (($year % 4 == 0) && ($year % 100 != 0))) { echo "$year is a leap year."; } else { echo "$year is not a leap year."; } ?>
Dry Run
Let's trace the year 1900 through the code to see if it is a leap year.
Input Year
year = 1900
Check divisibility by 400
1900 % 400 = 300 (not zero), so condition false
Check divisibility by 4 and not by 100
1900 % 4 = 0 (true), 1900 % 100 = 0 (true), so combined condition false
Result
1900 is not a leap year
| Step | Condition | Result |
|---|---|---|
| Divisible by 400? | 1900 % 400 == 0 | False |
| Divisible by 4? | 1900 % 4 == 0 | True |
| Not divisible by 100? | 1900 % 100 != 0 | False |
| Leap Year? | False || (True && False) | False |
Why This Works
Step 1: Divisible by 400
If the year divides evenly by 400, it is always a leap year because it accounts for century years.
Step 2: Divisible by 4 but not 100
If the year divides evenly by 4 but not by 100, it is a leap year because normal leap years occur every 4 years except centuries.
Step 3: Otherwise not leap
If neither condition is met, the year is not a leap year.
Alternative Approaches
<?php $year = 2024; $date = DateTime::createFromFormat('Y-m-d', "$year-02-29"); if ($date && $date->format('m-d') === '02-29') { echo "$year is a leap year."; } else { echo "$year is not a leap year."; } ?>
<?php function isLeapYear(int $year): bool { return ($year % 400 == 0) || (($year % 4 == 0) && ($year % 100 != 0)); } $year = 2024; echo isLeapYear($year) ? "$year is a leap year." : "$year is not a leap year."; ?>
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of arithmetic and logical operations regardless of input size, so it runs in constant time O(1).
Space Complexity
The program uses a fixed amount of memory for variables and no extra data structures, so space complexity is O(1).
Which Approach is Fastest?
The direct arithmetic check is fastest and simplest; using DateTime is more readable but slower due to object creation.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic check | O(1) | O(1) | Fastest and simplest |
| DateTime class | O(1) | O(1) | Readability and built-in validation |
| Function encapsulation | O(1) | O(1) | Code reuse and clarity |