php for loop associative array what is the use of & symbol to the variable
In PHP, using the & (ampersand) symbol before a variable in a foreach loop allows you to modify array elements directly by assigning them by reference.
Without the &, PHP creates a copy of the value for each iteration. Any changes you make to that variable inside the loop will only affect the copy, leaving the original array unchanged.
How it works
- Direct Modification: When you use
foreach ($array as &$value), the$valuevariable points to the actual memory location of the array element. - Efficiency: Using a reference can prevent unnecessary copying of large data sets, which may improve performance in specific scenarios.
- Associative Arrays: It works identically for associative arrays. You use the syntax
foreach ($array as $key => &$value)to modify the values while keeping access to their named keys.
Example: Modifying an Associative Array
In this example, we directly update the prices in an associative array:
$prices = [
"Apple" => 10,
"Banana" => 20,
];
// Use & to modify the original array values
foreach ($prices as $item => &$cost) {
$cost = $cost * 1.1; // Increase each price by 10%
}
// Result: $prices["Apple"] is now 11
Important Warning: Using unset()
According to the Official PHP Manual, the reference to the last element remains active even after the loop ends. If you later reuse that same variable name, you might accidentally overwrite the last item in your array.
To prevent this, it is standard practice to destroy the reference using unset() immediately after the loop:
foreach ($array as &$value) {
// modification logic
}
unset($value); // Breaks the reference to the last element