2

I'm trying to look through an array of records (staff members), in this loop, I call a function which returns another array of records (appointments for each staff member).

foreach($staffmembers as $staffmember)
{   
        $staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
        //  print_r($staffmember['appointments'] works fine 
}

This is working OK, however, later on in the script, I need to loop through the records again, this time making use of the appointment arrays, however they are unavailable.

foreach ($staffmembers as $staffmember)
{                                                             
        //do some other stuff
        //print_r($staffmember['appointments'] no longer does anything
}

Normally, I would perform the function from the first loop, within the second, however this loop is already nested within two others, which would cause the same sql query to be run 168 times.

Can anyone suggest a workaround?

Any advice would be greatly appreciated.

Thanks

2
  • I assume that the second loop occurs in the same function in which the first loop occurs? Commented May 21, 2010 at 9:07
  • I'm not sure I understand. Loops do not have their own scope. At which point are you losing $staffmembers and why? Commented May 21, 2010 at 9:07

1 Answer 1

6

foreach iterates over a copy of the array. If you want to change the value, you need to reference it:

foreach($staffmembers as &$staffmember) // <-- note the &
{   
    $staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
    //  print_r($staffmember['appointments'] works fine 
}

From the documentation:

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

and

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

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

3 Comments

I think that's unrelated to his question. EDIT: ok, I think this is what he meant, not really a scoping issue, really.
@Artefacto: It is related to scope in a way. The copy is not visible outside the loop ;)
Well... the last copy of $staffmember will be visible outside the loop, so it's not really a scoping problem... =)

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.