How would I put together a PHP5 function that would find the current calendar week and return the dates of each day in the week as an array, starting on Monday? For example, if the function were run today (Thu Feb 25 2010), the function would return an array like:
[0] => Mon Feb 22 2010<br />
[1] => Tue Feb 23 2010<br />
[2] => Wed Feb 24 2010<br />
[3] => Thu Feb 25 2010<br />
[4] => Fri Feb 26 2010<br />
[5] => Sat Feb 27 2010<br />
[6] => Sun Feb 28 2010<br />
It doesn’t matter what format the dates are stored as in the array, as I assume that’d be very easy to change. Also, it’d be nice to optionally be able to supply a date as a parameter and get the calendar week of that date instead of the current one.
Thanks!
I suppose a solution would be to start by getting the timestamp that correspond to last monday, using
strtotime:But if you try with today (thursday), with something like this :
you’ll get :
i.e. last week… For strtotime, “last” means “the one before today”.
Which mean you’ll have to test if today is “last monday” as returned by
strtotimeplus one week — and, if so, add one week…Here’s a possible (there are probably smarter ideas) solution :
And now that we have the timestamp of “last monday”, we can write a simple
forloop that loops 7 times, adding 1 day each time, like this :Which will give us this kind of output :
Now, up to you to :
forloop so it stores the dates in an arraydatefunctionHave fun 😉