Foreach loop not updating the values
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?
As per comments by others, I was missing &
next to $button
so it was making a copy of my array and not returning it. So adding &
, kept the references and updated my array properly, BUT then another thing I was missing was the same - &
with $form
too.
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;
}
链接地址: http://www.djcxy.com/p/53020.html
上一篇: 在foreach循环内添加循环的PHP foreach
下一篇: Foreach循环不更新值