strings in PHP can be encapsulated with single or double plication.
When encapsulated with double-sided, what happens is that the variables present in the contents of the string are replaced by their value:
<?php
$a = 1;
$b = 2;
$c = 3;
echo "Resultado: $a+$b-$c."; // Resultado: 1+2-3.
?>
To get the result of the operation indicates, we have to give the proper instruction to PHP, making use of the parentheses to indicate that the result of the one between them should be concatenated:
<?php
$a = 1;
$b = 2;
$c = 3;
echo "Resultado: ".($a+$b-$c)."."; // Resultado: 0.
?>
Your case
When we try to perform operations in the concatenation of strings , we have to take into account that +
and -
takes precedence such as .
operator, giving results unexpected.
strings can be concatenated only with the .
operator.
Arithmetic operators in the course of concatenation, such as +
and -
will tell PHP that an arithmetic operation should occur:
Note: PHP will convert non-empty values and non-numeric values to 0
(zero) during an arithmetic operation:
<?php
$a = 1;
$b = 2;
$c = 3;
echo "Resultado: ".$a+$b-$c."."; // -1.
?>
Explain:
Decomposing what is happening in the course of the arithmetic operation:
<?php
$a = 1;
$b = 2;
$c = 3;
echo "Fase 01:<br>";
echo "Resultado: ".$a;
// Output: 'Resultado: 1'
// (concatenação normal)
echo "Fase 02:<br>";
echo "Resultado: ".$a+$b;
// Output: '2'
// ("Resultado: ".$a resulta em 0 dando 0+2 = 2)
echo "Fase 03:<br>";
echo "Resultado: ".$a+$b-$c;
// Output: '-1'
// (2-3 = -1)
echo "Fase 04:<br>";
echo "Resultado: ".$a+$b-$c.".";
// Output: '-1.'
// (-1 + "." = -1.)
?>
From the example above, you can see the operation performed by PHP until it reaches the value of -1.
in output . Anyway, unexpected results are what we can expect when we use arithmetic operators in conjunction with strings concatenation operators.