PHP: Check if date is a leap year.

In this tutorial, we are going to show you how to detect leap years using PHP.

In the code below, we created a custom PHP function that determines whether a given date is a leap year or not.

A leap year is a year that contains an extra day (366 days instead of 365). As a result, February in a leap year will contain one more day than usual. Note that leap years are sometimes referred to as “intercalary years” or “bissextile years”.

Take a look at the following PHP function:

/**
 * Function that detects whether a given date falls in
 * a leap year or not.
 *
 * @param null $date Optional
 * @return bool TRUE if it's a leap year. FALSE if it is not a leap year.
 */
function isLeapYear($date = null){
    //Use the current timestamp by default.
    $ts = time();
    //A specific year or date was given.
    if(!is_null($date)){
        //A year was provided by itself... probably.
        if(strlen($date) == 4){
            //Create a full date string.
            $date = $date . '-01-01';
        }
        $ts = strtotime("$date");
    }
    //If date "L" returns a 1 string, it was a leap year.
    if(date('L', $ts) == 1){
        return true;
    }
    //Otherwise, return false.
    return false;
}

The PHP function above uses the date function’s L format character to test whether a given date is a leap year or not.

If the date is a leap year, “L” will return the string “1”. Otherwise, it will return the string “0”.

Note that we specifically used the word “string” there. In other words, don’t expect it to return an integer.

Below are a few examples of how to use this function.

Testing the current date:

//Testing the current year.
$isLeapYear = isLeapYear();
var_dump($isLeapYear); //Returns FALSE in 2019. It will return TRUE in 2020.

By default, the isLeapYear function will test the current year.

However, if you want to check a specific year, then you can pass it in as a parameter:

//Testing a specific year.
$isLeapYear = isLeapYear("2016");
var_dump($isLeapYear); //TRUE, because 2016 was a leap year.

In the example above, we passed in the string “2016” as a parameter. This results in the isLeapYear function returning a TRUE value.

You can also pass in a full date string:

//Testing to see if a date fell in a leap year.
$isLeapYear = isLeapYear("2012-11-16");
var_dump($isLeapYear); //True, because 2012 was a leap year.

This results in TRUE because 2012 was indeed a leap year.