Getting the current year in PHP is a common task, especially when dealing with dynamic content or generating reports. Thankfully, PHP provides a simple way to obtain the current year using the powerful date()
function.
Solution
// Get the current year
$currentYear = date('Y');
// Output the current year
echo "The current year is: $currentYear";
// Outputs
The current year is: 2024
In our above example, we provide the PHP date function the format of which we'd like our date displayed. In this case, we want to output the year, which is a capital "Y".
You can use this method to dynamically display the current year on your website or in your PHP applications. This is similar to the NOW()
function in MySQL, which we can also achieve using PHP. As PHP doesn't have that function we can use a similar function to achieve the same output as MySQL's NOW().
This approach is particularly useful for copyright notices, dynamic footers, or any other places where you want to automatically display the current year. For example, in a website footer. There are also other ways to display dates in PHP including how to convert a date.