PHP: Check if date is a leap year.

This is a short guide on how to detect leap years using PHP. In the code below, I have 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, the 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:

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 I specifically used the word “string” there. i.e. Don’t expect an integer.

Here are a few examples of this function being used.

Testing the current date:

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

If you want to check whether a certain year is a leap year, you can pass it in as a parameter:

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:

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

Facebook Comments