Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:
$a=array(1 => "A");
$b=&$a[1];
$c=$a; 
$c[1]="C";
echo $a[1];

Output : C (But i am expecting the output to be A )

Apparently, array is not referenced by '=' sign.

$c=$a; < this should make a copy of $a and assign it to $c . but why does reference take place here?

Moreover, if we simply remove the second line ( $b=&$a[1]; ), or replace it with ($b=&$a;), it behaves as expected.

Any explanation as to why this happens?

share|improve this question
    
PHP References Explained. – The Alpha Oct 7 '13 at 12:09
    
@RecoveringSince2003 : Sorry, that doesn't seem to answer my question. I know how references work in php. – user2816220 Oct 7 '13 at 12:14

1 Answer 1

From the php manual

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value. Example:

/* Assignment of array variables */
$arr = array(1);
$a =& $arr[0]; //$a and $arr[0] are in the same reference set
$arr2 = $arr; //not an assignment-by-reference!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* The contents of $arr are changed even though it's not a reference! */

In, your case, you have

$a=array(1 => "A");
$b=&$a[1]; // this line is making it as ref (ref preserved)
$c=$a; 
$c[1]="C";
echo $a[1];

If you write

$b=&$a; // then it's normal as expected.

Then this will result A not C

echo $a[1]; // A

Read more on php.net and (it's also confusing to me and can't explain it more than this, honestly!)

share|improve this answer
    
thanks :) that helps :D – user2816220 Oct 11 '13 at 14:52
    
@user2816220, You are welcome :-) – The Alpha Oct 11 '13 at 14:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.