Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation Enquires Welcome

All Dates of a Year Into an Array with PHP

All Dates of a Year Into an Array with PHP

On one of our aviation websites , we use a version of our Hiztory WP plugin to render a large amount of aviation history relevant to each day of the year (it's actually an enhanced version of the plugin that we're testing). As part of the process we had the need to generate a list of all the days in the year (in a loop) so as to create a readable text sitemap and, more importantly, an XML sitemap suitable for the likes of Google.

The following PHP function will load all the days of a defined year into an array.

1
<?php 
2
/*
3
 All Dates of a Year Into an Array with PHP
4
 http://www.beliefmedia.com/php-year-array
5
*/
6
 
7
function beliefmedia_year_array($year) {
8
 
9
  $range = array();
10
  $start = strtotime($year.'-01-01');
11
  $end = strtotime($year.'-12-31');
12
 
13
  do {
14
   $range[] = date('Y-m-d',$start);
15
   $start = strtotime(&quot;+ 1 day&quot;,$start);
16
  } while ( $start <= $end );
17
 
18
 return $range;
19
}

To render the array on your page, you should use the following:

1
/* Wrap in pre tags */
2
echo print_r(beliefmedia_year_array(2017));

Of course, if you chose to loop through the array and print the result directly to the page, you could use something similar to the following. In this example, I'm printing a formatted date (the code is to be used in the function above).

1
<?php 
2
foreach ($range AS $ranges) {
3
  $linkdate = strtolower(date('F-d',$start));
4
 echo $linkdate . '<br>';
5
}

I used a similar function to create the XML sitemap linked to below.

Example

If you want to see an example, you can view the XML sitemap that was the motivation for the above code here .

Download


Title: All Dates of a Year Into an Array with PHP
Description: All Dates of a Year Into an Array with PHP. Used to print out date-based XML sitemaps.
  Download • Version 0.2, 506.0B, zip, Category: PHP Code & Snippets

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Connecticut)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment