<?php
function wheresTheMonkey() {
//A
$months = array();
for ($i=6; $i>=0; $i--) {
$months[$i]["start"] = mktime(0,0,0, date("m")-(1*$i), 1, date("Y"));
}
print_r($months);
//B
foreach ($months as &$month) {
$month["end"] = strtotime("now +1 month", $month["start"]);
}
print_r($months);
//C
foreach ($months as $month) {
printf("%s\t\t%s\n",date("d F y", $month["start"]), $month["start"]);
}
}
print '<pre>';
wheresTheMonkey();
print '</pre>';
?>
This caused me a headache today - monkey business everywhere. If you don't get the gotcha;
$month
is still a pointer / reference to an array element in $months
, so doing another foreach assigns a new value to $months[0]
when you set $month
!It's too easy to forget in PHP...
No comments:
Post a Comment