2

I am trying to get the sum of a property inside an each loop. Here is my code:

    $client_systems_count = 0;
    $client->accounts->each(function ($account) use ($client_systems_count) {
        dd($account->systems->count());
        $client_systems_count += $account->systems->count();
    });
    dump($client_systems_count);

Any idea why it isn't working? I assume that even though I change the $client_systems_count variable inside the loop every time it goes to the next element inside the collection it resets to it's initial value. So which is the correct approach to get the total systems count?

1 Answer 1

7

This is your problem:

$client->accounts->each(function ($account) use ($client_systems_count) {

Every time the function runs, it uses the $client_systems_count of the outer scope. Which is 0.

In order to modify that value, you need to pass it by reference:

$client->accounts->each(function ($account) use (&$client_systems_count) {
                                                 ^ here
Sign up to request clarification or add additional context in comments.

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.