Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I update data in an array with foreach loop?

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?

like image 237
Choy Avatar asked Oct 23 '12 02:10

Choy


3 Answers

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']);
like image 112
newfurniturey Avatar answered Oct 19 '22 00:10

newfurniturey


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

like image 41
aziz punjani Avatar answered Oct 19 '22 02:10

aziz punjani


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

like image 22
Lucas Mezêncio Avatar answered Oct 19 '22 02:10

Lucas Mezêncio