0

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.

1
  • I suspect you're re-using one of the reference variables somewhere, forgetting it's still a reference. Seeing the rest of the code might help Commented Oct 2, 2009 at 14:55

2 Answers 2

5

Using references in foreach loops is asking for trouble :) I've done that several 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.

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

2 Comments

I think references will fit good here. Thats where references are for, right?
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".
4

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

1 Comment

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

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.