Re: How can i use & symbol as an array when using foreach lo
Posted: Sat Aug 13, 2011 1:43 pm
Never used it before on a foreach loop, just when passing parameters via functions, so I went looking. And yes you can for PHP 5 and later.
From http://www.php.net/manual/en/control-st ... oreach.php
Prior to PHP5 (and if you want even with PHP5), you would do something like:
Thanks for asking, it taught me something new!
-Greg
PS. for memory conservation, the first method is the better method
From http://www.php.net/manual/en/control-st ... oreach.php
Code: Select all
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>Code: Select all
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $key=>$value) {
// $value actually doesn't get used here, but required in the structure above
$arr[$key] *= 2;
}
// $arr is now array(2, 4, 6, 8)
?>-Greg
PS. for memory conservation, the first method is the better method