I want to print out a text before printing the output of the calculation, without storing the text in a variable. How can I achieve this?
Here is my code:
$x = 5;
$y = 10.5;
echo "add: 5+6 =" . $x + $y;
I want to print out a text before printing the output of the calculation, without storing the text in a variable. How can I achieve this?
Here is my code:
$x = 5;
$y = 10.5;
echo "add: 5+6 =" . $x + $y;
This code calculate addition $x + $y, then convert to string, then concatenate to string "add: 5+6=" (see https://www.php.net/manual/en/function.strval.php)
$x = 5;
$y = 10.5;
echo "add: 5+6 = ". strval($x + $y);
About your code
See https://www.php.net/manual/en/language.operators.precedence.php : concatenation operators have higher precedence than arithmetic operators.
Your original code is the same as:
$x = 5;
$y = 10.5;
echo (int)("add: 5+6 =" . $x) + $y;
That means: first, concatenate string "add: 5+6 =" . $x
add 5+6 =5
then cast to int (that return 0)
(int)("add: 5+6 =5")
then add $y
0 + 10.5
then echo it
echo 10.5;
So this is why your code return 10.5
<?php
$x = 5;
$y = 10.5;
echo "add: 5+6 =" . ($x + $y); // automatic converts to `string`
You can try this.
<?php
$x = 5;
$y = 10.5;
$z = $x + $y;
echo "add: 5+6 = " . $z;
?>
<?php
$x = 5;
$y = 10.5;
printf("add: 5+6 = %f", $x + $y);
?>
You can do it by concatinating your variable
<?php
$x = 5;
$y =10.5;
$z=$x+$y;
echo "add: ".$x."+".$y." = ". $z;
?>
add: 5+10.5 = 15.5