-1

How to make PHP reutrn "1 + 2 = 3"? and not just 3

function show_sum($a, $b) {
return "$a + $b = " $a + $b;
}
echo show_sum(1,2);

I have already tried:

return '$a + $b' = " . $a + $b;

I just get 3

jeromegamez
  • 3,348
  • 1
  • 23
  • 36
Alexey Tseitlin
  • 1,031
  • 4
  • 14
  • 33

3 Answers3

3

You're missing the concatenation operator. Your return statement should be:

return "$a + $b = ". ($a+$b);
jhansen
  • 284
  • 2
  • 10
  • 1
    You're right, it needs parenthesis. Order of operations causes the string portion to concatenate with $a. PHP then attempts to add 3 to a string, which defaults to NULL and ultimately returns 3. – jhansen Apr 26 '15 at 16:07
1

Put the result into brackets.

function show_sum($a, $b) {
    return "$a + $b = " . ($a + $b);
}
pavel
  • 26,538
  • 10
  • 45
  • 61
  • 2
    Why should the OP "try this"? Please add an explanation of what you did and why you did it that way not only for the OP but for future visitors to SO. (Also how could you even post an answer when the question was closed?!) – Rizier123 Apr 26 '15 at 15:59
  • Panther broke the internet. – Devon Bessemer Apr 26 '15 at 16:09
1

This does work. I think the problem is mixing string values and numeric values. I've made everything a string.

<?php
function show_sum($a, $b) {
$sum = $a + $b;
$return_string = "$a + $b = " . $sum;
return $return_string;
}
echo show_sum(1,2);
?>
BigScar
  • 343
  • 3
  • 9