tags:

views:

52

answers:

1
+2  Q: 

PHP scope question

Hi,

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

+6  A: 

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.

Felix Kling
I think that's unrelated to his question. EDIT: ok, I think this is what he meant, not really a scoping issue, really.
Artefacto
@Artefacto: It is related to scope in a way. The copy is not visible outside the loop ;)
Felix Kling
@Felix Well... the *last* copy of `$staffmember` *will* be visible outside the loop, so it's not really a scoping problem... =)
deceze
Thanks for clearing that up for me!:)
Dan
@deceze: OK :).
Felix Kling