PHP Array of DateTime seems skewed -
i trying create function create array of datetime(s). dates want every saturday in given year.
i have function when values stored in array, begin second saturday of year , extend first saturday of following year.
note following displays list of saturdays generated function , after couple of blank lines displays saturdays store in array.
<?php define ('sql','y-m-d'); define ('br','<br/>'); function allsaturdays ($year){ $endofyear = "$year-12-31"; $interval = new dateinterval("p7d"); $year--; $workingdate = "$year-12-31"; $workingdate = strtotime ($workingdate); $workingdate = strtotime ("next saturday",$workingdate); $workingdate = date ("y-m-d",$workingdate); $workingdate = new datetime ($workingdate); $result[] = new datetime; while ($workingdate->format(sql) <= $endofyear ) { $result[] = $workingdate; echo $workingdate->format (sql).br; $workingdate->add ($interval); $workingdate = new datetime ($workingdate->format(sql)); //echo $workingdate->format (sql)."#".br;; }// while unset ($workingdate); return $result; }//function $sats = allsaturdays(2016); echo "<br/.<br/>"; foreach ($sats $saturday) echo $saturday->format(sql)."*<br>"; ?>
however, if store date (2016-01-02) correct values in array.
no doubt i'm missing simple. appreciated.
dave
you modifying datetime object after placed in array.
this add array:
$result[] = $workingdate;
and line after adds 7 days it:
$workingdate->add($interval);
calling add modifies original. if want make sure you're working on copy, call clone first or use datetimeimmutable
instead of datetime
.
here's new version of code using datetimeimmutable:
function allsaturdays ($year){ $endofyear = new datetimeimmutable("$year-12-31"); $workingdate = new datetimeimmutable("first saturday of january " . $year); while ($workingdate <= $endofyear ) { $result[] = $workingdate; $workingdate = $workingdate->modify('+7 days'); }// while return $result; }//function
here's version not use datetimeimmutable
function allsaturdays ($year){ $endofyear = new datetime("$year-12-31"); $workingdate = new datetime("first saturday of january " . $year); while ($workingdate <= $endofyear ) { $result[] = $workingdate; $workingdate = clone $workingdate; $workingdate->modify('+7 days'); }// while return $result; }//function
Comments
Post a Comment