Explanation about concatenation of variables in PHP

Asked

Viewed 35,368 times

6

I always wonder how to concatenate strings with variables in PHP. I have some difficulty understanding the question of double or single quotes.

I would like an answer to clarify why one or the other should be used and why in practice.

  • I reopened the question, it was closed with one that spoke only of quotes and no concatenation.

4 answers

13

The concatenation operator of strings is the point .

For example:

$ddd  = '34';
$fone = '32105691';

echo '(' . $ddd . ') ' . $fone;

This example works the same with double quotes:

echo "(" . $ddd . ") " . $fone;

That’s how you concatenate strings in PHP.


Another issue is the difference between single and double quotes. A string amid single quotes is not processed except by the escape characters. For example, if you want the string contains a single quote character, you will need to use the escape character \, thus:

$texto_com_aspas = 'Temos aspas aqui => \' <= e isto é bom.';

If you use the dollar sign $ or the brackets { and } with single quotes, they will not be interpreted (as with double quotes). They will remain literal, as they are:

$texto_normal = 'A variável $texto_normal contém cifrão e {colchetes}.';

If you use double quotes will have to use the exhaust for double quotes, for the dollar and for the brackets:

$texto_com_aspas = "Temos aspas aqui => \" <= e isto é bom.";

$outro_texto = "Temos cifrão e colchetes aqui => \{ \$ \} <= e isto é bom.";

In both cases, to get a backslash you will need to duplicate it, because in your first appearance the character \ is understood as "escape":

$texto_com_barra_invertida = 'Uma barra: \\ e mais' . " outra barra: \\ beleza?";

Now the main difference is that using double quotes, both the dollar sign $ as for the square brackets { and } activate the processing of interpolation in string, through which the contents of variables can be inserted into the text.

For example:

$ddd  = '34';
$fone = '32105691';

echo "($ddd) $fone";

// resultado => (34) 3210-5691

This can only be done with double quotes. With single quotes it would look like this:

echo '($ddd) $fone';

// resultado => ($ddd) $fone

However, in some cases we need to use brackets, because without them it would be difficult to tell where the variable to be interpolated begins and where it ends. Behold:

$singular = 'peixe';
$texto = "Eu comprei muitos $singulars!";

I want you to show up "I bought many fish!"

However, how will PHP guess that my variable calls $singular and not $singulars (with "s" at the end)?

For this case, and more complex ones, we use the brackets:

$texto1 = "Eu comprei muitos {$singular}s!";

$texto2 = "Seja bem vindo, {$usuario->nome}!";

$texto3 = "Quantidade: {$item['quantidade']} Preço: {$item['preco']}";

$texto4 = "$propriedade => {$item[$propriedade]}";

All these interpolation examples require double quotes.


I particularly never use double quotes. I always use single quotes. I’ve seen too many double quotes being abused - with strings that are illegible without syntax Highlight. I usually use the function sprintf when I want to interpolate. My advice is: be friends with the other developers who will work with you, and avoid double quotes.

  • Well completed your answer. Great job!

3

Basically, single quotes and double quotes have the same concatenation effect as strings. In terms of performance, single quotes are more efficient than double quotes (it simply concatenates the strings, while double quotes have a different dynamic of including each substring in a variable and then concatenating them). This difference however has little relevance nowadays, since this additional 'delay' when concatenating with double quotes is basically irrelevant.

$nomeCompleto = 'Nome'.'Sobrenome';

or

$nome = 'Teste1';
$sobrenome = 'Teste2';
$completo = $nome . $sobrenome;

3

The advantage of using double quotes is that they interpret values. For example:

<?php
$nome = "Juca";
echo "Olá {$nome}!"; // Olá Juca! ?>

0

All this is described in the PHP manual.

Making a complement, the comma can also be used as a concatenation character.

In benchmark tests the use of the comma, instead of the point, is more performatic. It is usually used when applying micro-optimizations.

About the use of single quote or double quote, I prefer single quote, because performatically it is better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.