When dealing with $row in the foreach loop you aren't dealing with the same variable that is in the array, but a copy. If you want to make lasting changes you need to use a reference.
function addLength($toAdd, $added){
$result = $toAdd;
foreach ($result as & $row) {
foreach ($added as $key => $value) {
if($key == $row['id'] ){
$row['length'] = $value;
}
}
}
var_dump($result);
return $result;
}
Please make sure to note that a reference will still exist after the foreach loop has completed. It will contain a reference to the last element of your $result array. To stop this you would need to manually unset the reference.
function addLength($toAdd, $added){
$result = $toAdd;
foreach ($result as & $row) {
foreach ($added as $key => $value) {
if($key == $row['id'] ){
$row['length'] = $value;
}
}
}
var_dump($row); // Outputs the last element of your $result array
unset($row);
var_dump($row); // Now undefined.
var_dump($result);
return $result;
}
Just as an FYI, you can optimise your code and get rid of the second foreach loop, it's just not necessary. This would do the same:
function addLength($toAdd, $added){
$result = $toAdd;
foreach ($result as & $row) {
if ( array_key_exists($row['id'], $added) ) {
$row['length'] = $added[$row['id']];
}
}
var_dump($result);
return $result;
}
Now rather than looping through $added for every item in $toAdd you just check to see if the data is there (by checking for the array key) and if it is, use it.
foreachcreates copies of the data. If you change$row(the copy), the original array ($result) won't be affected. Try changing the foreach to use references instead:foreach ($result as &$row)(the added & sign).