views:

121

answers:

2

I'm using references to alter an array:

foreach($uNewAppointments as &$newAppointment)
{
 foreach($appointments as &$appointment)
 {
  if($appointment == $newAppointment){
   $appointment['index'] = $counter;
  }
 }
 $newAppointment['index'] = $counter;
 $newAppointments[$counter] = $newAppointment;

 $counter++;
}

If I print the array contents, then I receive the expected result. When I iterate over it, all elements seem to be the same (the first).

When I remove the reference operator & in the inner array, all goes normal, except index isn't set.

+4  A: 

If you do this, you must unset $newAppointment when you exit the loop. Here is the relevant entry.

dnagirl
Found another solution here: http://nl2.php.net/manual/en/language.references.whatdo.php#73631 But you're answer is better.
Ikke
+5  A: 

Using references in foreach loops is asking for trouble :) I've done that serveral times, and I always rewrote that code.

You should to it as well. Like this:

foreach($uNewAppointments as $newAppointmentKey => $newAppointment)
{
        foreach($appointments as $appointmentKey => $appointment)
        {
                if($appointment == $newAppointment){
                        appointments[$appointmentKey]['index'] = $counter;
                }
        }
        $uNewAppointments[$newAppointmentKey]['index'] = $counter;
        $$uNewAppointments[$newAppointmentKey][$counter] = $newAppointment;

        $counter++;
}

Though I have just rewritten it "mechanically", so it will probably not work. But it's to get the idea of how to achieve the same effect, without the side effects. You are still modifying the original arrays in this loop.

Palantir
I think references will fit good here. Thats where references are for, right?
Ikke
Well, not exactly. You already have a "handle" for the element (its key) for free, so there is in reality no real advantage of using them. References are to avoid duplication of data, which here does not occur. The fact is that references within a foreach loop are inherently very confusing, and may introduce subtle bugs. For example, in your code, $newAppointment and $appointment will remain set and pointing to the last item of the array even after the 2 loops. It is easy to re-use those names later, and it may be difficult to understand why is the wrong element changing "unexpectedly".
Palantir