As strings in PHP can be encapsulated with single or double plica.
When encapsulated with double plica, 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, using the parentheses to indicate that the result of what is 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 during the concatenation of strings, we have to take into account that the +
and the -
shall take precedence as the operator .
, giving rise to unexpected results.
As strings can be concatenated only with the operator .
.
Arithmetic operators in the course of concatenation, such as +
and the -
will indicate to 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.
?>
Explaining:
Breaking down 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.)
?>
For the example above, you can see the operation performed by PHP until you reach the value of -1.
in the output. Anyway, unexpected results are what we can expect when we use arithmetic operators in conjunction with concatenation operators strings.
You have to do the account first and put in a variable, then concathens with the strings.
– Jorge B.
Have you tried
$arr_3[$i]."<sup>".($arr_22[$i]-$contador+$eletrons)."</sup>"
?– Sergio
Oh yes. Dude, you solved.. What’s the parenthesis logic?
– HiHello
'Cause when I do it without it comes right back?
– HiHello
Not putting the parentheses he does not know that it is a function, think that "-" for example is part of the string.
– Jorge B.
I tried several ways, but I did not arrive in 3d 10-30+26 from
$arr_4[] = "$arr_3[$i]<sup>".$arr_22[$i]-$contador+$eletrons."</sup>";
was that the correct line that generated this result?– gmsantos