13

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?

0

3 Answers 3

34

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']);
1
  • 1
    @Choy You may also want to see the first warning here.
    – John V.
    Oct 23, 2012 at 3:15
7

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()

1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.