0

Why in this code is $a equal to 21? I am giving to $b the value of $a by reference, why is $a changing as well??

$a = '1';
$b = &$a;
$b = "2$b";
echo $a.", ".$b;
2
  • A downvote with no explanation does not help, I gladly accept the downvote if it has a comment :-) Commented Oct 11, 2018 at 12:32
  • 7
    From php.net/manual/en/language.references.whatare.php "References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on" So setting $b as a reference to $a, is not setting the value but the variable context. So this is the content of variable a should be the same as variable b. Commented Oct 11, 2018 at 12:33

2 Answers 2

1

Notice that you define the variables with single or double quotes (both are ok) That's how Php knows you mean a string

Regarding the reference - the meaning of reference, is that $b points to $a, so its not really a variable

and lastly, this: $b = "2$b"; is basically string concatanation

Sign up to request clarification or add additional context in comments.

Comments

1

Here's a simple explanation

$a = '1';
$b = &$a; // Sets $b to a reference to $a


echo $b."<br>"; // $b value is still one

$b = "2$b"; // here u write "2 and $b = 1" which means b = 21 and also Sets $a to 21

echo $a.", ".$b;

So your output is 21,21 hope you understand

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.