Re: Assign values in foreach-loop
| From: | Edward Vermillion | Date: | Wed, 07 Sep 2005 17:22:14 +0000 |
| Subject: | Re: Assign values in foreach-loop | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-221977@lists.php.net to get a copy of this message | ||
Sabine wrote:
Hello to all,
is it possible to assign values to the array for which I do the foreach-loop?
foreach ($_SESSION['arr1'] as $arr1) {
foreach ($_SESSION['arr2'] as $arr2) {
if ($arr1['id'] == $arr2['id']) {
$arr1['selected'] = true;
}
} }
I think $arr1 is only a temp-var, so the assignment won't reflect on $_SESSION['arr1'] . Is that right?
Surely I can do it with a for-loop, but those arrays are a bit complex and a foreach would be much easier to read.
Thanks in advance for your answers
Sabine
Short answer is no.
foreach works on a copy of the array, so any chnges you make inside the foreach loop are "lost" once you're outside of it. Although *inside* the foreach the changes *are* valid.
What you can do is:
$newArray = array();
foreach ($_SESSION['arr1'] as $arr1) {
foreach ($_SESSION['arr2'] as $arr2) {
if ($arr1['id'] == $arr2['id']) {
$newArray['selected'] = true;
}
} }
Then reference $newArray instead of $arr1.