I’m trying to run a clean up job on data in an array, specifically converting epoch time to YYYY-MM-DD.
I tried this function originally:
foreach ($data as $row) {
$row['eventdate'] = date('Y-m-d', $row['eventdate']);
}
echo '<pre>';
print_r($data);
echo '</pre>';
However the foreach loop didn’t update the data when I output it.
The following for loop did work:
for ($i=0; $i<count($data); $i++) {
$data[$i]['eventdate'] = date('Y-m-d', $data[$i]['eventdate']);
}
Why did the first loop fail and the second work? Aren’t they the same?
When you’re using a
foreachloop in the way you currently are,foreach ($data as $row) {,$rowis being used “by-value”, not “by-reference”.Try updating to a reference by adding the
&to the$row:Or, you can use the key/value method: