Core PHP

Using Foreach Loops with References

This is an example PHP program that demonstrates how to use references inside a foreach loop to assign values to array entries.

UsingForeachWithReferences.php

<?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 &dollar;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 &dollar;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 &dollar;iaArray[".$i."] is ".$iaArray[$i]."<br />";
}

?>
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.