Expected Input:
getDatesFromRange( '2010-10-01', '2010-10-05' );
Expected Output:
Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )
Expected Input:
getDatesFromRange( '2010-10-01', '2010-10-05' );
Expected Output:
Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )
Here's a way of doing this using Carbon https://github.com/briannesbitt/Carbon:
This, of course, can be tweaked to not use Carbon. The $first and $last parameters passed to the function are Carbon instances.
Here is the another solution. Please check this.
look on this
use like
Here is a function, that will return date ranges in both directions and it works on PHP >=5.2.2 :
Use example:
demo
I love a solid one-liner!
My php discovery of the day was that
array_push()
returns the new number of elements in the array.I managed to check for the end date match, increment $x, and push new elements all within the two-part condition statement of an empty while loop.
The most similar function to mine on this page is drolex's (which I didn't actually find until after I wrote mine, if you believe me). I did some speed tests across large and small date ranges and they seem to beat each other just as often -- so I'm calling them equal performers. Here are some other comparisons:
date()
,strtotime()
, and two array functions.$x
.$date
array is not necessary for my function, I can declare it in the function parameters and spare the line (likewise with$x
).**Just a couple of important notes:
1- Date strings MUST BE validated before being fed to the function.
2- The above function can only handle forward moving date ranges. If you want backward moving date ranges, simply reverse the date order in the function call and add a minus after
$x=
. (Pretty slick, eh?)One more extension/consideration...
Imagine you have a multi-cultural (or sloppy) user base, and your function MUST be able to receive start and end dates in different valid formats AND you need to be able to output the array in any of the valid formats? By minor adjustment, I've provided a solution for that.
By "valid" I mean
YYYY-MM-DD
,MM/DD/YYY
, andDD-MM-YYYY
, these are massively popular standards world-wide, if another format is necessary then usability would come down tostrtotime
's comprehension of it.Here is the Demo.
Code:
Output
Now some people don't 100% trust strtotime() because of some buggy behaviors. I think I've read that it will foul up when trying to jump a month from a leap-day. However, unless someone can reproduce it to prove me wrong, strtotime() is never going to let you down when you are only incrementing by one day.