-1

I have a function that adds a dollar sign and formats a number to two decimal places. Like a cheap convert to currency.

function money($num){
    echo "$" . number_format($num , 2 , "." , ",");
  }

Then I echo a string like this:

echo "Your new sun-total is: " . money($subtotal);

I get:

$25.75Your new sub-total is:

Any insight would be greatly appreciated. Thanks.

  • 1
    `echo` is a construct. Which means it controls program flow. The function should `return` the value instead. – Sherif Aug 15 '21 at 01:08
  • 1
    Does this answer your question? [Difference between echo and return in php?](https://stackoverflow.com/questions/10903659/difference-between-echo-and-return-in-php) – kmoser Aug 15 '21 at 04:42

2 Answers2

1

This line:

echo "Your new sun-total is: " . money($subtotal);

calls the money() function, and appends the result to the text before echoing it.

Your money() function echoes the formatted number before returning, so you see that first. money() doesn't return anything, so your initial line then echoes the text with nothing appended.

Change your money() function like this:

function money($num){
    return "$" . number_format($num , 2 , "." , ",");
  }
0

I think you're confusing the echo keyword and the return keyword.

Echoing a value will output it from the program. This is similar to printing values as you would do in other languages. Returning a value will set the function call's return value and exit the function, which is what you want here.

The reason you are getting the dollar amount before you are getting the text is because you are echoing the value when the function gets called. After that, PHP will automatically return nothing at the end of your function since you have not specified a return value. It will then concatenate "Your new sun-total is: " with an empty string and echo that as well.

You can fix this by rewriting your money function to look like this:

function money($num){
  return "$" . number_format($num , 2 , "." , ",");
}
Gav Hern
  • 76
  • 1
  • 7