What is the purpose of & in PHP? [duplicate]

3

I have the following code snippet:

$a = '1';
$b = &$a;
$b = "2$b";
echo $a.", ".$b;

Output:

21, 21

I noticed that there is no assignment to the variable $a except for the fact that $b = &$a using & , that in the end, the result is changed. I did not understand very well, so I wonder:

What does & mean for this situation? What would be the goal? And at what point is this used?

    
asked by anonymous 05.06.2017 / 14:42

2 answers

6

The difference in whether to use & is that, with & a reference is made, you will be using the same variable in memory, even if the variable name is different, if you change one, change the other and vice versa.

Without the & you make a copy of the variable, if you change one of the two, one will not affect the other, they are independent and point to different places in memory.

<?php

$a = '1'; // $a = '1'
$b = &$a; // $b = $a = 1
$b = "2$b"; // $b = "2($a)" = "21"
echo $a.", ".$b; // Como $b faz referência a $a e vice versa, $b foi alterado para 21 na linha acima, logo a saída será igual, 21 para ambos os valores
    
05.06.2017 / 14:47
4

The & is used to assign or modify a variable by reference.

$b = &$a

Means that every time $a is alerted $b will have the same value because value of $b always points to $a . If the value $b change $a will have the same value.

How does this code work:

$a = '1';
$b = &$a; //ambas as variáveis tem valor 1
$b = "2$b"; // $b recebe o número 2 seguido do seu valor anterior ou seja 1 e modifica/sobrescreve o valor '$a'
echo $a.", ".$b; //
    
05.06.2017 / 14:48