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 foreach
loop in the way you currently are, foreach ($data as $row) {
, $row
is being used "by-value", not "by-reference".
Try updating to a reference by adding the &
to the $row
:
foreach ($data as &$row) {
$row['eventdate'] = date('Y-m-d', $row['eventdate']);
Or, you can use the key/value method:
foreach ($data as $index => $row) {
$data[$index]['eventdate'] = date('Y-m-d', $row['eventdate']);
The initial example only passes row by value and not by reference.
From the docs
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference
Hence either pass by reference
foreach ($data as &$row) {
$row['eventdate'] = date('Y-m-d', $row['eventdate']);
}
or use the more explicit syntax
foreach ($data as $key => $value) {
$data[$key]['eventdate'] = date('Y-m-d', $value['eventdate']);
}
Also of importance is this warning in the docs
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()
Because in the foreach statement, you need to pass the second argument by reference.
Check the documentation: http://www.php.net/manual/en/control-structures.foreach.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With