What is. = in php?

7

What is .= in PHP? I'm not sure if it's a concatenation or multiplication.

    
asked by anonymous 17.11.2016 / 14:49

3 answers

11

Used to concatenate strings . It adds new text to a text that already exists in the variable.

$texto .= "um texto aqui";

is the same as

$texto = $texto . "um texto aqui".

Another example:

$texto = "";
for ($i = 0; $i < 10; $i++) {
    $texto .= $i . " ";
}
echo $texto;

See working on ideone and in PHP SandBox .

I found a answer in the OS with a curiosity about performance of using concatenation and constructing string with classes specialized . In PHP the concatenation is very cheap because the string is mutable. In C #, because it is immutable, it costs costly if you do it in a large proportion , so StringBuilder goes much better when you need this pattern in large numbers. But note that using it right, in C # the performance is much better, as you would expect.

Multiplication would be

$valor *= 2;

If this is in a loop, it will double the value of each loop.

    
17.11.2016 / 14:53
7

It is the same as += in other languages. Because PHP is not typed, .= is used for strings , it adds text to the right of the existing text in string .

$texto = "Hello, ";
$texto .= "World";
echo($texto); 

//Saída > Hello, World
    
17.11.2016 / 14:55
1

I would say that .= is a form of contraction (a shortening) for the concatenation syntax, in order to make it simpler.

In PHP, the . operator is responsible for concatenating strings .

Example:

$ab = 'a' . 'b'

var_dump($ab); // ab

However, the .= operator will concatenate a string by combining it with the existing value in the variable.

$ab = 'a';

$ab .= 'b';

var_dump($ab); // 'ab'

Thus, using the .= operator makes the operation easier in some cases than using . .

Example:

$texto = "o rato roeu"

$texto .= " a roupa do rei de Roma"

If you were to use the . operator, your code would be slightly larger:

$texto = "o rato roeu"

$texto = $texto . " a roupa do rei de Roma"
    
18.11.2016 / 13:55