1

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;
}

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm interested, how is it "worse"? Could you please elaborate? :)
@NiftyDude: It performs one more lookup. Not much of a problem, so quotes around worse.
0

Alternative way that doesn't use reference: (&)

foreach($output as $i => $row) {
   $output[$i]['reviewCount'] = 1;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.