Re: reference variables
| From: | Shawn McKenzie | Date: | Fri, 22 May 2009 12:44:20 +0000 |
| Subject: | Re: reference variables | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-292938@lists.php.net to get a copy of this message | ||
kranthi wrote:
> i have this script
>
> <?php
> $x = 1;
> $y = 2;
> $a1 = array(&$x, &$y);
> $a2 = array($x, $y);
> $a2[0] = 3;
> print_r($a1);
> print_r($a2);
> ?>
>
> i am expecting
>
> Array
> (
> [0] => 3
> [1] => 2
> )
> Array
> (
> [0] => 3
> [1] => 2
> )
>
>
> while i m getting
>
> Array
> (
> [0] => 1
> [1] => 2
> )
> Array
> (
> [0] => 3
> [1] => 2
> )
>
>
> any ideas why this is happening?? or am i missing something..?
> the same is the case when i replace
> $a2[0] = 3; with
> $a1[0] = 3;
> $x = 3;
>
> Kranthi.
>
$a2[0] was assigned the value of $x or 1, so when you change $a2[0],
that's all that changes. You have changed the value 1 to 3. $a1[0] is a
reference to $x, so if you change $a1[0] it will change $x, but not
$a2[0] because it is not a reference to $x.
--
Thanks!
-Shawn
http://www.spidean.com