1

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;
Proteeti Prova
  • 1,079
  • 4
  • 25
  • 49

6 Answers6

3

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

GabrieleMartini
  • 1,665
  • 2
  • 19
  • 26
2
<?php
$x = 5;
$y = 10.5;

echo "add: 5+6 =" . ($x + $y); // automatic converts to `string`
xayer
  • 413
  • 4
  • 11
1

You can try this.

<?php
    $x = 5;
    $y = 10.5;
    $z = $x + $y;
    echo "add: 5+6 = " . $z;
?>
Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
1
<?php
  $x = 5;
  $y = 10.5;
  printf("add: 5+6 = %f", $x + $y);
?>

alprnkeskekoglu
  • 288
  • 1
  • 7
1

try this:

$x = 5;
$y = 10.5;
$z=$x+$y;
echo "add:5+6 =".$z;
PHP Geek
  • 3,949
  • 1
  • 16
  • 32
1

You can do it by concatinating your variable

<?php
$x = 5;
$y =10.5;
$z=$x+$y;

echo "add: ".$x."+".$y." = ". $z;
?>

output

add: 5+10.5 = 15.5