Pass by reference. Technically, PHP passes everything be reference now, and it's more commonly seen when passing values to functions.
Although passed by reference, whenever a function argument is modified, PHP clones a copy of the argument within local scope, and it's the copy that is modified.
Code: Select all
function test($x,$y) {
return (++$x * ++$y);
}
$A = 2;
$B = 3;
echo test($A,$B);
echo $A;
echo $B;
However, when you use the &, PHP doesn't clone a copy when the argument is modified, but modifies the original variable.
Code: Select all
function test(&$x,&$y) {
return (++$x * ++$y);
}
$A = 2;
$B = 3;
echo test($A,$B);
echo $A;
echo $B;
Within the scope of a foreach loop,
$d is a clone of the data element from the array, and any modification to $d is against the cloned copy that is discarded once the loop ends; but if prefixed by &, it's the actual element of the array that is modified.
Note, I forgot to mention, but you should also unset $d once the loop ends, otherwise you may get unpredictable results.
Code: Select all
foreach($data as $d) {
$date = $d['Event']['date'];
$prettyDate = date('M j,Y', strtotime($date));
$d['Event']['prettyDate'] = $prettyDate;
}
unset($d);
You might think that this would unset the last element in the array, but it doesn't. Using the & with $d actually creates a new variable $d that is a pointer to the array element. Unsetting $d after the loop removes the pointer variable $d, but doesn't unset the array element that it's a pointer to.