How Do You Write a Leap Year Program in PHP? (With Examples & Output)

A leap year program in PHP checks whether a year is divisible by 4, not divisible by 100, or divisible by 400. You can use simple conditional statements like if-else to determine this. PHP makes the logic easy with both arithmetic and built-in date functions.
Points to cover:

  • Leap year validation is used in date handling, billing cycles, scheduling, and calendars.
  • PHP powers many web applications, so correct date logic avoids errors.
  • Good starter program for learning PHP conditions.

Key Takeaways

  • Leap year rule: ÷ 4 → leap year; ÷ 100 → not leap year; ÷ 400 → leap year.
  • Best PHP method: Conditional logic using modulus operator.
  • Alternative: Use PHP’s built-in DateTime class.
  • Common use-cases: Calendars, finance apps, subscription systems.

What Is a Leap Year in PHP?

A leap year in PHP follows the same rules as the Gregorian calendar. A year is considered a leap year if:

  • It is divisible by 4
  • But not divisible by 100,
  • Unless it is also divisible by 400

This rule ensures February has 29 days in leap years. PHP programs use these conditions to validate dates, calculate billing cycles, and prevent date-related errors.

PHP Leap Year Logic Explained (Beginner Friendly)

PHP uses the modulus operator % to check divisibility.
The expression:

$year % 4

returns 0 if the year is divisible by 4.

Leap year logic in PHP works like this:

  1. If a year is divisible by 400 → leap year
  2. Else if divisible by 100 → not a leap year
  3. Else if divisible by 4 → leap year
  4. Otherwise → not a leap year

This makes the logic easy and accurate across all years.

PHP Program to Check Leap Year (If-Else Example)

Code Example

<?php
$year = 2024;

if ($year % 400 == 0) {
    echo "$year is a leap year.";
} elseif ($year % 100 == 0) {
    echo "$year is not a leap year.";
} elseif ($year % 4 == 0) {
    echo "$year is a leap year.";
} else {
    echo "$year is not a leap year.";
}
?>

Output

2024 is a leap year.

This approach is the most commonly used and works for all date-related validations.

PHP Program to Check Leap Year Using Ternary Operator

Code Example (One-Liner)

<?php
$year = 2024;

echo ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 != 0))
     ? "$year is a leap year."
     : "$year is not a leap year.";
?>

Output

2024 is a leap year.

This method is compact and ideal for quick checks or inline validations.

PHP Program to Validate Leap Year with DateTime Class

PHP’s DateTime class provides an even simpler method.
The format("L") option returns:

  • 1 → leap year
  • 0 → not a leap year

Code Example

<?php
$year = 2024;

$date = new DateTime("$year-01-01");

if ($date->format("L") == 1) {
    echo "$year is a leap year.";
} else {
    echo "$year is not a leap year.";
}
?>

Output

2024 is a leap year.

This method is extremely reliable because it uses PHP’s internal date engine.

When Should You Use Each Method?

Which PHP leap year method is fastest?

The if-else and ternary versions are slightly faster because they use direct arithmetic operations.
Best for:

  • Competitive coding
  • High-performance computations
  • Simple scripts

Is DateTime reliable for leap year checks?

Yes. DateTime->format("L") is the most reliable option because it depends on PHP’s internal date validation system rather than manual conditions.
Best for:

  • Calendar apps
  • Billing systems
  • Databases and enterprise apps

Leap Year PHP Code

php

  

Explanation of the Code

The provided PHP code is a simple program to check if a year is a leap year. Here’s a breakdown of how it works:

  1. The `isLeapYear` function takes a year as its argument. It checks if the year is a leap year using conditional logic.Inside the function, two main conditions are evaluated:
    – First condition: The year must be divisible by 4 but not by 100. This is expressed as `$year % 4 == 0 && $year % 100 != 0`.

    – Second condition: Even if the year is divisible by 100, it will still be a leap year if it’s divisible by 400, written as `$year % 400 == 0`.

  2. If either condition is satisfied, the function returns `true`, indicating a leap year.The `$year` variable is set to 2024, and the `isLeapYear` function is called. It prints whether the year is a leap year or not.

Output:

2024 is a leap year.

Practical Applications of Leap Year Calculation in PHP

  1. Holiday Booking Systems: In companies like Booking.com, knowing when a leap year occurs can help accurately calculate vacation lengths and manage bookings, especially for February holidays.
    
    function isLeapYear($year) {
        return ($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0);
    }
    $year = 2024;
    if (isLeapYear($year)) {
        echo "$year is a leap year.";
    } else {
        echo "$year is not a leap year.";
    }
    
    Output: “2024 is a leap year.”

  2. Subscription Services: Companies like Spotify use leap year calculations to ensure accurate subscription billing cycles over periods that include February.
    
    function getDaysInMonth($month, $year) {
        if ($month == 2) {
            return isLeapYear($year) ? 29 : 28;
        } else {
            return in_array($month, [4, 6, 9, 11]) ? 30 : 31;
        }
    }
    $daysInFebruary = getDaysInMonth(2, 2024);
    echo "February 2024 has $daysInFebruary days.";
    
    Output: “February 2024 has 29 days.”

  3. Data Analysis Tools: Tools like Microsoft Excel use leap year functionality to compute date differences accurately for reports spanning multiple years.
    
    $date1 = new DateTime('2023-02-28');
    $date2 = new DateTime('2024-03-01');
    $interval = $date1->diff($date2);
    echo "Difference is " . $interval->days . " days.";
    
    Output: “Difference is 366 days.”

Interview: Leap Year PHP

  1. How can I check if a year is a leap year in PHP using a different approach than the widely-known formula?
    You can use PHP’s built-in `DateTime` class. This approach doesn’t require you to remember the leap year formula. Simply create a `DateTime` object for February 29th and check the format output.
    
    $year = 2024;
    $date = DateTime::createFromFormat('Y-m-d', "$year-02-29");
    $isLeap = $date && $date->format('Y') == $year;
    echo $isLeap ? "Leap year" : "Not a leap year";
        

  2. Is it possible to determine leap year logic using bitwise operations in PHP?
    Yes, you can use bitwise operations to check for leap years. It involves checking the multiples of 4, 100, and 400 using bitwise AND.
    
    $isLeap = ($year & 3) == 0 && (($year % 100 !== 0) || ($year & 15) == 0);
    echo $isLeap ? "Leap year" : "Not a leap year";
        

  3. How can I create a function in PHP that returns all leap years in a given range?
    You can write a simple function that loops through each year in the range and checks if it’s a leap year using the standard logic.
    
    function leapYearsInRange($start, $end) {
        $leapYears = [];
        for ($year = $start; $year <= $end; $year++) {
            if (($year % 4 === 0 && $year % 100 !== 0) || ($year % 400 === 0)) {
                $leapYears[] = $year;
            }
        }
        return $leapYears;
    }
    print_r(leapYearsInRange(2000, 2020));
        

  4. Can leap year checks in PHP be affected by the server settings?
    Generally, leap year checks aren’t affected by server settings, as these calculations are based on logical operations and not server configurations.


  5. Is there a one-liner code to check if a year is leap in PHP?
    Yes, you can use a conditional operator for a concise leap year check.
    
    $isLeap = ($year % 4 === 0 && $year % 100 !== 0) || ($year % 400 === 0) ? "Leap year" : "Not a leap year";
    echo $isLeap;
        

  6. How do I handle errors when checking leap years using PHP functions?
    When dealing with date functions, wrap your code in a try-catch block to handle potential exceptions.
    
    try {
        // Your leap year logic here
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
        

Our AI-powered php online compiler offers a seamless coding experience. Instantly write, run, and test your 'php' code with the help of AI. It's designed to streamline your coding process, making it quicker and more efficient. Try it out, and see the difference AI can make!

Conclusion

'Leap Year in PHP' isn't just a coding task, it's a stepping stone in your programming journey. Completing it boosts your confidence and understanding of PHP. Give it a go; you'll feel a genuine sense of accomplishment. For more programming languages, explore Newtum.

Edited and Compiled by

This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She's passionate about helping beginners understand technical topics in a more interactive way.

About The Author