Difference between single and double quotes in PHP

Asked

Viewed 20,131 times

76

What is the difference between single and double quotes in PHP?

Yesterday I was working with a string from a google json I used explode('\n', .. to separate a string.

When I used the explode in "Mon Jul 7, 2014 \n\u003cbr", with " gave me:

array(1) { [0]=> string(25) "Mon Jul 7, 2014 \u003cbr" }

When I used the explode in 'Mon Jul 7, 2014 \n\u003cbr', with ' gave me:

array(2) { [0]=> string(16) "Mon Jul 7, 2014 " [1]=> string(8) "\u003cbr" }

The above was just a practical example I came across.
It would be interesting to know what are the differences, in PHP, between ' and " ?

6 answers

65


Single quotes

The PHP documentation defines that single quotes are simple literal, unprocessed. The only exceptions for escape are the single quotes themselves ('\'') and the bar ('\\').

Example:

$teste = 1;
echo 'A caixa d\'água está vazia. \\ $teste';

The exit will be:

The water tank is empty. $test

Double quotes

Already the double quotes will be processed, supporting more escape characters such as \n, \r, \t and others. In addition, variables will be expanded (or interpolated), for example: "Meu nome é $nome!".

Example:

$teste = 1;
echo "A caixa d\'água está vazia. \\ $teste $teste2";

The exit will be:

The water tank is empty. 1 $teste2

Note that $teste2 is not defined, so the string will not be expanded.

Heredoc and Nowdoc

In addition to these two ways of representing strings in the code, there are also heredoc and the Nowdoc, which allow you to add String blocks more easily. Note that the heredoc works as double quotes, while the nowdoc works like simple quotes.

Example of heredoc:

$interpolacao = 'INTERPOLAÇÃO';

$str = <<<EOD
Exemplo de String
$interpolacao funciona aqui dentro
EOD;

Exit:

String Example

INTERPOLATION works in here

Example of nowdoc:

$interpolacao = 'INTERPOLAÇÃO';

$str = <<<'EOD'
Exemplo de String
$interpolacao não funciona aqui dentro
EOD;

Exit:

String Example

$Interpolate doesn’t work in here

17

The difference between single and double quotes is in the use.

Double quotes allow:

to) that variables are interpreted within it:

$nome = "bob";
echo "meu nome é $nome";

b) use Use of exhaust pipes such as : \n ,\r, \t, \v, \e, \f, \\, \$, \";

c) invoking methods/properties using the full syntax, that is, they are necessary {}:

echo "{$pessoa->getNome()}";

Single quotes allow:

to) only the escapes \' and \\:

echo 'I\'m here'; //i'm here
echo 'I\'m \r\n here'//não vai gerar a quebra de linha.

13

As stated in the other answers, single quotes are literal and double quotes are interpretative.

Because they have a different memory consumption, an important point when choosing to use single or double quotes is the content that will be added to them.

If using plain text, prefer to use simple quotes that the memory consumption will be less because there is no need for PHP to try to interpret the content.

$simples = 'Meu nome é Raul'; //consome menos memória
$duplas = "Meu nome é Raul"; //consome mais memória

Now, if you need to concatenate this text with variables it is better to use double quotes instead of using dot (.).

$simples = 'Meu nome é '.$nome; //consome mais memória
$duplas = "Meu nome é $nome"; //consome menos memória

10

Single quotes

Recognise the content literally, everything will be treated as text:

<?php
$valor = 10;
$variavel = 'meu número é $valor';
echo $variavel;
// Saida: meu número é $valor

Double quotes

Recognizes escape characters \n \t \r and variáveis in the content:

<?php
$valor = 10;
$variavel = "meu número é $valor";
echo $variavel;
// Saida: meu número é 10

8

In PHP, the single quote is not interpretive, it is a string and only that, the double is processed, so it can contain variables that will be converted when executing the string.

For example:

$foo = 'bar';

echo "Variavel $foo"; // Variavel bar
echo 'Variavel $foo'; // Variavel $foo

2

In order to reproduce the comparative performance that many places present by placing the strings with simple quotes as faster, I used the tool Profiling Blackfire in both versions.

Version using single quotes

<?php // single.php

$string = 'Anderson Carlos Woss';

Version using double quotes

<?php // double.php

$string = "Anderson Carlos Woss";

Note that unlike most other places I won’t be inside a repeat loop, as this tends to insert too much noise into the sample due to various considerations in memory management that the interpreter does. One string fixed can be allocated at compile time and only reused at run time, which would cause the result not to accurately reproduce the sample space. I also did not use the language’s own time functions to measure the time and did not use input and output functions to also insert noise in the result. The script has as its function only to declare the string of the two distinct forms.

Space of 1000 samples has been taken and the result will be based on the average between them:

Sampling using single quotes

inserir a descrição da imagem aqui

Wall Time      87µs
I/O Wait        n/a
CPU Time        n/a
Memory       35.9KB
Network         n/a     n/a     n/a
SQL             n/a     n/a

Sampling using double quotes

inserir a descrição da imagem aqui

Wall Time      86µs
I/O Wait        n/a
CPU Time        n/a
Memory       35.9KB
Network         n/a     n/a     n/a
SQL             n/a     n/a

That is, in 1000 samples, the average difference between the two versions was 1 μs (1 microsecond, or 0.000001 seconds), even pointing to double quotation marks as shorter time. The only conclusion that comes out of this is that it makes no difference between using single or double quotes in terms of performance to define strings static. It is worth commenting that the I/O, CPU and network times were null as expected and the memory used was the same, because in both solutions the same content was used.

  • 1

    If you are going to see the individual level, it means that using simple quotes implied 1 ns more for each round. This time can be explained easily by the decay of the electron wave function

Browser other questions tagged

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