I have a question about PHP and the use of pointers and variables.
The following code produces something I wouldn’t have expected:
<?php
$numbers = array('zero', 'one', 'two', 'three');
foreach($numbers as &$number)
{
$number = strtoupper($number);
}
print_r($numbers);
$texts = array();
foreach($numbers as $number)
{
$texts[] = $number;
}
print_r($texts);
?>
The output is the following
Array
(
[0] => ZERO
[1] => ONE
[2] => TWO
[3] => THREE
)
Array
(
[0] => ZERO
[1] => ONE
[2] => TWO
[3] => TWO
)
Notice the ‘TWO’ appearing twice in the second array.
It seems that there is a conflict between the two foreach loops, each declaring a $number variable (once by reference and the second by value).
But why ? And why does it affect only the last element in the second foreach ?
The key point is that PHP does not have pointers. It has references, which is a similar but different concept, and there are some subtle differences.
If you use var_dump() instead of print_r(), it’s easier to spot:
… prints:
Please note the
&symbol that’s left in the last array item.To sum up, whenever you use references in a loop, it’s good practice to remove them at the end:
… prints the expected result every time.