Unexpected behaviour with PHP array references

核能气质少年 提交于 2020-01-03 06:01:08

问题


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:


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




回答2:


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.



来源:https://stackoverflow.com/questions/1509979/unexpected-behaviour-with-php-array-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!