Reputation: 207
I am trying to update the reviewCount on each array to 1. I am confused why my foreach loop will not update it. Any help would be greatly appreciated
$output:
Array(
[1] => Array(
[category] => Category 1
[country] => USA
[date] => 2012-04-07 23:50:49
[name] => Product 1
[reviewCount] =>
)
[2] => Array(
[category] => Category 1
[country] => USA
[date] => 2012-04-07 23:50:49
[name] => Product 1
[reviewCount] =>
)
Code:
foreach ($output as $row) {
$row['reviewCount'] = 1;
}
Upvotes: 1
Views: 92
Reputation: 60516
Alternative way that doesn't use reference: (&
)
foreach($output as $i => $row) {
$output[$i]['reviewCount'] = 1;
}
Upvotes: 0
Reputation: 437376
It does not update it inside $output
because you are setting the review count on a copy of the row. Do this instead:
foreach ($output as &$row) { // <-- added &
$row['reviewCount'] = 1;
}
This way you are operating on a reference to the row, which has the same effect of operating on the original row itself. See this page for more details.
Another way to do the same (more intuitive possibly, although "worse" technically) would be
foreach ($output as $key => $row) {
$output[$key]['reviewCount'] = 1;
}
This way you are operating on the original row again -- obviously, since you are fetching it from inside the array manually using its key.
Upvotes: 3