Forum Moderators: coopster
$arr = array
(
'key0' => array(0,1),
'key1' => array(2,3),
'key2' => array(4,5)
);
foreach( $arr as $key => $sub )
{
$sub[1] = 'X';
}
Being a Javascripter, I expected that this would mean that:
echo $arr['key0'][1]; [blue]// 'X'[/blue] It took me a while to figure out that the sub-arrays were being copied into the variable, $sub, so anything I do inside the loop has no effect on my data structure.
The Question
Is there some syntax that I can use to force the
foreach enumeration to throw out references rather than values?
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.
..and I'm running PHP 4.
Would it be a headache trying to install PHP 5 alongside it?
I imagine that would only involve swapping a couple of Apache config directives.
I also like running PHP in WSH - that's the unknown factor it this point.
I'm doing this for a college assignment - server-side forms whatnot. You can imagine. I started off by trying to apply the kind of approach that I would on the client-side, with all the configureables nicely mapped out at the top. I just got into a mess.
If there were a book entitled, Learning PHP for users of languages beginning with J, it would begin thusly:
"At least one of the P's in PHP stands for 'Perverse'".
-----
If you are familiar with the works of the band, Gong, you will know that PHP stands for something else entirely.
Changing values of the array directly is possible since PHP 5 by passing them as reference.
Prior versions need workaround:
Example 11-8. Collection
<?php
// PHP 5
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */
// Workaround for older versions
foreach ($colors as $key => $color) {
$colors[$key] = strtoupper($color);
}
print_r($colors);
?>
Anyway, if you get stuck on PHP nuances, post 'em here. You've offered so much great assistance over in the js forum that we enjoy returning the favor.
I'll play with that snippet when I get to my PHP 5 installation at college.
I'm a big fan & collector of CHM files, so I view the PHP manual like that. I'd better watch out for updates too.