Re: Assign by reference...
| From: | Victor | Date: | Tue, 13 Jun 2000 13:31:03 +0000 |
| Subject: | Re: Assign by reference... | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-1710@lists.php.net to get a copy of this message | ||
Yes, I think Rasmus is right. You are reseting your reference on line 5.
It seems to me when you assign a new array to $mult_arr, it's address
stays the same. Thus all entries in $multiples_arr point to the same
array (your last one). I think you were trying to use $mult_arr as
your temporary variable. Then, when you assigned a new array, you
thought that it would just point to a new memory location. However,
as your example shows, it just reset the values and put new ones into
same memory. (I think your example would work great in Java). I am not
sure how to make $mult_arr be a temp var and get new mem location on each
assignment; lets wait for the PHP authors to update the documentation.
Try this, this gave me what you wanted.
1 $num_arr = array(1, 2, 3);
2 $multiples_arr = array();
3 while (list($key, $val) = each($num_arr))
4 {
5 $mult_arr[$key] = array($val, $val*10, $val*100);
6 $multiples_arr[] = &$mult_arr[$key];
7 }
8
9 while (list($key, $mult_arr) = each($multiples_arr))
10 {
11 print join(",",$mult_arr)."<BR>\n";
12 }
Output:
X-Powered-By: PHP/4.0.0
Content-type: text/html
1,10,100<BR>
2,20,200<BR>
3,30,300<BR>
Benjamin Berman wrote:
> I'm having a problem with the new assign by reference feature in PHP4.
> Consider the following code; it's an artificial example that takes an
> array of numbers, for instance (1,2,3) and transforms it into an array
> of arrays, where each array contains multiples of the original number,
> for instance ((1,10,100), (2,20,200), (3, 30, 300)). Here is the code:
>
> 1 $num_arr = array(1, 2, 3);
> 2 $multiples_arr = array();
> 3 while (list($key, $val) = each($num_arr))
> 4 {
> 5 $mult_arr = array($val, $val*10, $val*100);
> 6 $multiples_arr[] = &$mult_arr;
> 7 }
> 8
> 9 while (list($key, $mult_arr) = each($multiples_arr))
> 10 {
> 11 print join(",",$mult_arr)."<BR>\n";
> 12 }
>
> I would expect to get the output:
>
> 1,10,100
> 2,20,200
> 3,30,300
>
> But instead, I get the following:
>
> 3,30,300
> 3,30,300
> 3,30,300
>
> This is counter-intuitive with respect to other programming languages
> I've used. I can guess what's happening underneath to make PHP display
> this behavior, but it still seems to contradict my notion of what
> "assignment by reference" means. Is there any way to get PHP to do what
> I want it to do here?
>
> Thanks,
> ben.
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, e-mail: php-general-unsubscribe@lists.php.net
> For additional commands, e-mail: php-general-help@lists.php.net
> To contact the list administrators, e-mail: php-list-admin@lists.php.net