This is an example PHP program that demonstrates how to use references inside a foreach loop to assign values to array entries.
<?php // Create an array: [0, 10, 20, 30, 40] $iaArray = []; for ($i = 0; $i < 5; ++$i) { $iaArray[] = 10 * $i; } // The initial array for ($i = 0; $i < 5; ++$i) { echo "The value of $iaArray[".$i."] is ".$iaArray[$i]."<br />"; } // Assign values without references. The value is copied, in this case. foreach($iaArray as $iValue) { $iValue = 7; } echo "<hr />"; for ($i = 0; $i < 5; ++$i) { echo "The value of $iaArray[".$i."] is ".$iaArray[$i]."<br />"; } // Assign values with references. foreach($iaArray as &$iValue) { $iValue = 7; } // As a precaution, unset the reference so that it is not inadvertently assigned some other value. unset($iValue); echo "<hr />"; for ($i = 0; $i < 5; ++$i) { echo "The value of $iaArray[".$i."] is ".$iaArray[$i]."<br />"; } ?>
© 20072025 XoaX.net LLC. All rights reserved.