I have trying to modify values using pointers within nested foreach loops in PHP.. The following line however does not seem work:
// Assign a the attribs value to the array
$link_row['value'] = $args[ $u_value ];
The variable $args[ $u_value ]; is populated and can be output without issue, but when i added it to the $link_row reference it just doesnt seem to set..
foreach ($unique_links as $link_id => &$link_attr)
{
foreach($link_attr as &$link_row)
{
foreach($link_row as $u_attr => &$u_value)
{
if ($u_attr == 'attribute_name')
{
// Assign a the attribs value to the array
$link_row['value'] = $args[ $u_value ];
// If one of the values for the unique key is blank,
// we can remove the entire
// set from being checked
if ( !isset($args[ $u_value ]) )
{
unset($unique_links[$link_id] );
}
}
}
}
}
You must always unset variables after using them in a foreach. Even if you have two foreach(..) statements one right after the other. Even if you have a foreach(..) inside another foreach(..). No exceptions!
foreach ($unique_links as $link_id => &$link_attr)
{
foreach($link_attr as &$link_row)
{
foreach($link_row as $u_attr => &$u_value)
{
if ($u_attr == 'attribute_name')
{
// Assign a the attribs value to the array
$link_row['value'] = $args[ $u_value ];
// If one of the values for the unique key is blank,
// we can remove the entire
// set from being checked
if ( !isset($args[ $u_value ]) )
{
unset($unique_links[$link_id] );
}
}
}
unset($u_value); // <- this is important
}
unset($link_row); // <- so is this
}
unset($lnk_attr); // <- and so is this, even if you reached the end of your program or the end of a function or a method and even if your foreach is so deeply indented or on such a long line that you're not sure what code might follow it, because another developer (maybe even you) will come back and read the code and he might not see that you used a reference in a foreach
Here's another fun piece of code that messed up a big project not long ago:
foreach ($data as $id => &$line) {
echo "This is line {$id}: '{$line}'\n";
$line .= "\n";
}
echo "And here is the output, one line of data per line of screen:\n";
foreach ($data as $id => &$line) {
echo $line;
}
The fact that someone didn't unset($line) right after the first foreach(..) really messed up the data in the array, because &$line was a reference and the second foreach(..) assigned it a different value as it looped through the data and it kept overwriting the last line of data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With