Set a seasonal image in PHP that will change with season

By Faruque Ahamed Mollick

How cool will it be if an image on the web page could be changed depending on the season? What, if in winter there will be an image that represents the winter and in summer another image come and take that place? Will it not be really cool?

Yes, that’s possible in PHP. In PHP we can set the seasonal image on a web page. We will have a set of pictures and only one of those pictures will be shown depending upon the season.

Ajaxify Weather Forecast PHP Script Source Code

Get random word from English dictionary in PHP tutorial



Below is our PHP function that will show seasonal image:

<?php
function seasonal_image()
{

$current_date = new DateTime();
$spring = new DateTime('March 20');
$summer = new DateTime('June 20');
$autumn = new DateTime('September 22');
$winter = new DateTime('December 21');

  switch(true) {
      case $current_date >= $spring && $current_date < $summer:
        // Image for Spring
         $img_url = "spring.png";
        break;

      case $current_date >= $summer && $current_date < $autumn:
        // Image for Summer
         $img_url = "summer.png";
        break;

      case $current_date >= $autumn && $current_date < $winter:
        // Image for Autumn
         $img_url = "autumn.png";
        break;

      default:
        // Image for Winter
         $img_url = "winter.png";
    }
    return $img_url;

 }
?>

In the above code, we have created a PHP function that will return the image URL depending upon the date range we provide in a switch case statement inside the function. Here inside the switch case function, we have set the image path or image URL for the different season or date range.

We have set the date range for 4 seasons. These are spring, summer, autumn, and winter. We are going to see 4 different images for these 4 different seasons.

Generate PDF from HTML template in PHP using Dompdf

Now below is the usage of the function:

<img src="<?php echo seasonal_image(); ?>">

It will display the image on the web page that is matching with our date range inside the function. Thus for winter, spring, summer and autumn, it shows different image as we have set four different images.

 

Leave a Reply

Your email address will not be published. Required fields are marked *