Reputation: 13930
If I need to change a function parameter, I can use foo(&$x)
and the function can modify it.
I need something like this in a foreach loop,
$x=array(1,2,3);
foreach($x as &$i) $i=1;
var_dump($x);
results with some strange "&int(1)"...
array(3) {
[0]=>
int(1)
[1]=>
int(1)
[2]=>
&int(1)
}
But, of course, this is not the syntax (for what I whant)... It is possible to do this with PHP?
It is not "so elegant" to use for
(now it works!),
$x=array(1,2,3);
for($i=0; $i<count($x); $i++) $x[$i]=1;
var_dump($x);
Upvotes: 1
Views: 251
Reputation: 13930
My homework affter good comments and answer at the comments.
As @lonesomeday says, "that is precisely the right syntax". The PHP guide shows that
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value)
$value = $value * 2;
unset($value); // break the reference with the last element
and, as @Wrikken say, needs the unset
.
As @MarcB20 says, take care..."foreach($x as &$i) $i=1;
is VERY dangerous. $i
will REMAIN a reference for the duration of your code (or until you unset it), and you can unwittingly modify the contents of the array by reusing the variable in some other context down the road"...
So, you can use an "intermediate elegance" syntax,
foreach ($arr as $key=>$value) {
// ... use $value ...
$arr[$key] = $anothervalue;
}
prefer to use simple for
(with array_keys
if an array associative) if the $value not used.
Upvotes: 0
Reputation: 237935
First off, this isn't technically a pointer. It is a reference. Before using them in your code, I'd suggest you get familiar with how they work in PHP by reading the manual section that explains them.
In this case, your code is actually correct, as documented in the manual page for foreach
. foreach($x as &$i)
is precisely the way to do this. Your confusion apparently comes from the output of var_dump
:
&int(1)
This is precisely what you should expect. The &
signifies that another variable is a reference pointing to this value. This is because $i
continues to be a reference to the last element in the array even after the loop is over. This is potentially dangerous, because code elsewhere in your file may modify $i
and therefore your array without you wanting it to.
It is probably good practice to unset
$i
after the loop is over to avoid this.
Upvotes: 1
Reputation: 324710
When a loop ends, the iterator still holds the last value used. In this case, the last item in the array. So it's still referenced. It doesn't really matter unless you try to reuse $i
later, in which case you may get some weird results.
It would be safer to do something like this:
foreach($x as $k=>$v) {
$x[$k] = 1;
}
Upvotes: 0