Foreach loop not updating the values

时间:2015-07-08 15:57:42

标签: php foreach

I've for a few forms on the page. Before rendering them in my views, I create them dynamically in PHP with their buttons and elements. I want to adjust the tabindexes dynamically, so basically once I have all the forms ready at the end of the PHP script, I do the following:

public function fixTabindexes($forms) {

    $tabindex = 1;      

    $forms = count($forms) > 1 ? $forms : [$forms];

    foreach($forms as $form) {

        foreach($form['form'] as $element) {
            $element->setAttrib('tabindex', $tabindex++);
        }

        foreach($form['buttons'] as $button) {                                              
            $button['tabindex'] = $tabindex++;
        }

    }

    return $forms;

}

Elements get updated perfectly, but buttons don't. It feels as if the second foreach - $form['buttons'] is not saving the ['tabindex'] key and it's value. However, if I do a var_dump inside the foreach loop, it shows up fine.

What am I doing wrong?

1 个答案:

答案 0 :(得分:1)

根据其他人的评论,我在&旁边丢失了$button,因此它正在复制我的数组而不是返回它。所以添加&,保留引用并正确更新我的数组,但是我遗漏的另一件事情是相同的 - &同时$form

public function fixTabindexes($forms) {

    $tabindex = 1;      

    $forms = count($forms) > 1 ? $forms : [$forms];

    foreach($forms as &$form) {

        foreach($form['form'] as $element) {
            $element->setAttrib('tabindex', $tabindex++);
        }

        foreach($form['buttons'] as &$button) {                                              
            $button['tabindex'] = $tabindex++;
        }

    }

    return $forms;

}