I'm not quite clear on how to combine variables and strings typed directly.
Let's use the variable $test
:
$test="prueba";
Case 1.-
Enclosing the variable in double quotes " "
works:
echo "Esto es una $test";
Resultado
:
Esto es una prueba
Case 2.-
Enclosing the variable in single quotes ' '
doesn't work:
echo 'Esto es una $test';
Resultado
:
Esto es una $test
It seems that when we use double quotes the value of $test
is recognized, but it is not if we use single quotes.
But... let's try arrays.
We will work with this array:
$arr=array(array("id"=>1, "nombre"=>"Pedro"), array("id"=>2, "nombre"=>"Juan"));
Case 3.-
Read $arr
applying the same criteria of Case 1 :
foreach ($arr as $row){
echo "ID: $row['id']\n";
}
Resultado:
PHP Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)
And, as @Marcos comments at the bottom of this question, in this case this could also be done:
echo "ID: $row[id]\n";
That is, without the single quotes. As an additional note, values cannot be accessed in a sub-depth, meaning this would not be valid:
echo "ID: $row[prop][valor]\n";
Case 4.-
Ok, let's reverse the quotes:
foreach ($arr as $row){
echo 'ID: $row["id"]\n';
}
Resultado:
ID: $row["id"]\n
ID: $row["id"]\n
Does it seem that the same procedure echo
as above cannot be applied when reading an array?
Is the only alternative to leave out the variable that is captured with row
?
foreach ($arr as $row){
echo 'ID: '.$row["id"].'\n';
//O bien:
echo "ID: ".$row["id"]."\n";
}
Resultado:
ID: 1
ID: 2
The question
Having seen the cases above, I wonder why the echo does not recognize the variables between single quotes and why the method of case 1 does not work in case 3?
I raise the question because I always get confused when I have to use variables combined with handwritten strings.
I am going to answer you according to the PHP manual , a literal of type string can be specified in four different ways:
In order not to extend too much let's see the first two to your question.
single quote
The easiest way to declare a string is to use single quotes (the character
'
).Example:
double quote
If a string is formed with double quotes ("), PHP will interpret the following escape sequences as special characters:
Escaped characters:
Analysis of variables
When a string is specified using double quotes
""
or heredoc<<<EOT
, variables inside that string will be parsed.There are two types of syntax: one simple and one complex . The simple syntax is the most used and practical. Provides a way to embed a
variable
, a value of a ,array
or a property of aobject
within acadena
with minimal effort.Complex syntax can be recognized by the braces that delimit the expression.
simple syntax
If a dollar sign (
$
) is encountered, the parser will take the largest number of symbols to form a valid variable name . Delimiting the variable name with curly braces allows you to explicitly specify the end of the name.Example:
The result of the example would be:
Similarly, you can parse the index of a
array
or the property of aobject
.The result of the example would be:
Complex syntax (braces)
This syntax is not called complex because it is complex, but because it allows the use of complex expressions.
Any scalar variable , array element, or object property with a string representation can be included via this syntax. Simply write the expression the way it would appear outside the string, and delimit it with
{ y }
. Since{
it cannot be escaped, this syntax will only be recognized when the$
immediately follows the{
. Use{\$
to get a{$ literal
.Some examples:
Always use double quote strings (
""
) for concatenation.Put your variables in
"Esto es una notación {$variable}"
, because it's the fastest method that still allows complex expansions like"This {$var['foo']} es {$obj->awesome()}!"
. You can't do that with style"${var}"
.Feel free to use single quoted
''
strings for FULLY literal strings like array keys / values , variable values , etc., as they are a TINY bit faster when unparsed string literals are desired. But I had to do a billion iterations to find a measurable difference of 1.55%. So the only real reason I would consider using single-quote strings for my literals is for code cleanup , to make it very clear that the string is a literal.100 million iterations:
See more results of iterations .
Font Character strings (Strings) .
Single quotes are for literal strings : they don't replace variable references with their values, nor do they escape characters.
Whereas double quotes are for escaped strings : they accept variables, references (in braces, as shown below), and backslash-escaped characters:
Whenever possible use single quotes, because they are faster and safer, unless you need to escape values.
If you need to put double quotes inside an escaped string, you simply escape them: