[ACCEPTED]-Create an Array of the Last 30 Days Using PHP-date

Accepted answer
Score: 38

Try this:

<?php    
$d = array();
for($i = 0; $i < 30; $i++) 
    $d[] = date("d", strtotime('-'. $i .' days'));
?>

0

Score: 2

Here is advance latest snippet for the same,

$today     = new DateTime(); // today
$begin     = $today->sub(new DateInterval('P30D')); //created 30 days interval back
$end       = new DateTime();
$end       = $end->modify('+1 day'); // interval generates upto last day
$interval  = new DateInterval('P1D'); // 1d interval range
$daterange = new DatePeriod($begin, $interval, $end); // it always runs forwards in date
foreach ($daterange as $date) { // date object
    $d[] = $date->format("Y-m-d"); // your date
}
print_r($d);

Working 1 demo.

Official doc.

Score: 1

For those who want to show sales of the 4 past X days,
As asked in this closed question (https://stackoverflow.com/questions/11193191/how-to-get-last-7-days-using-php#=), this worked for me.

  $sales = Sale::find_all();//the sales object or array

  for($i=0; $i<7; $i++){
    $sale_sum = 0;  //sum of sale initial
    if($i==0){ 
    $day = strtotime("today"); 
  } else {
   $day = strtotime("$i days ago");
  }
  $thisDayInWords = strftime("%A", $day);

  foreach($sales as $sale){
    $date = strtotime($sale->date_of_sale)); //May 30th 2018 10:00:00 AM
    $dateInWords = strftime("%A", $date);

    if($dateInWords == $thisDayInWords){
        $sale_sum += $sale->total_sale;//add only sales of this date... or whatever
    } 
  } 
  //display the results of each day's sale
  echo $thisDayInWords."-".$sale_sum; ?> 

 } 

Before 3 you get angry: I placed this answer here 2 to help someone who was directed here from 1 that question. Couldn't answer there :(

Score: 0

You can use time to control the days:

for ($i = 0; $i < 30; $i++)
{
    $timestamp = time();
    $tm = 86400 * $i; // 60 * 60 * 24 = 86400 = 1 day in seconds
    $tm = $timestamp - $tm;

    $the_date = date("m/d/Y", $tm);
}

Now, within 2 the for loop you can use the $the_date variable 1 for whatever purposes you might want to. :-)

Score: 0
$d = array();
for($i = 0; $i < 30; $i++)
    array_unshift($d,strtotime('-'. $i .' days'));

0

More Related questions