I'm studying PHP for an advanced exam. The practice test said that the first iteration is better than the second. I not figure out why. They both iterate the contents of an array just fine.
// First one:
foreach($array as $key => &$val) { /* ... */ }
// Second one:
foreach($array as $key => $val) { /* ... */ }
The practice test said that the first iteration is better than the second.
That isn't the best advice. They're different tools for different jobs.
The &
means to treat the variable by reference as opposed to a copy.
When you have a variable reference, it is similar to a pointer in C. Accessing the variable lets you access the memory location of the original variable, allowing you to modify its value through a different identifier.
// Some variable.
$a = 42;
// A reference to $a.
// & operator returns a reference.
$ref = &$a;
// Assignment of $ref.
$ref = "fourty-two";
// $a itself has changed, through
// the reference $ref.
var_dump($a); // "fourty-two"
Reference example on CodePad.
The normal behaviour of foreach
is to make a copy available to the associated block. This means you are free to reassign it, and it won't affect the array member (this won't be the case for variables which are always references, such as class instances).
Copy example on CodePad.
Class instance example on CodePad.
Using a reference in a foreach
has some side effects, such as a dangling $val
reference to the last value iterated over, which can be modified later by accident and affect the array.
Dangling reference example on CodePad.
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