Categories
PHP

Date range PHP

You know Range from PHP? so this function does same but with given dates 😉

Usage:

//normal
$dates = date_range(strtotime('-1 month'), time());
//advanced, using all parameters
$dates = date_range(strtotime('-1 month'), time(),
'+1 day','Y-m-d',array('date'=>0,'count'=> 0),'date');

Function:


	/**
	 * get an array range with dates in a specific format
	 * @param  string $start      from
	 * @param  string $end        to
	 * @param  string $step       strtotime style
	 * @param  string $format     date format
	 * @param  array $array_fill default fill for the array to return
	 * @param  string $d_field      the field we use to put the date into
	 * @return array
	 */
	function date_range($start, $end, $step = '+1 day', $format = 'Y-m-d', $array_fill = NULL, $d_field = 'date')
	{
		//return array
		$range = array();

		if (is_string($start) === TRUE)
			$start = strtotime($start);
		if (is_string($end) === TRUE)
			$end   = strtotime($end);

		do
		{
			$date = date($format, $start);

			if (is_array($array_fill))
			{
				$array_fill[$d_field]  = $date;
				$range[] = $array_fill;
			}
			else
				$range[] 	= $date;

			$start 	= strtotime($step, $start);//increase

		} while($start <= $end);

		return $range;
	}