Reputation: 111
I'm still just learning PHP and not very far in. I'm trying to make a simple if/else loop work, and running up against an error in the first part of my code that I can't seem to find a solution for.
This is the first part of my program (the loop itself seems to be working fine):
<?php
echo $mealCost = "$" . 16.25 . "<br>";
echo $mealTip = "$" . 3.25 . "<br>";
echo $mealTax = "$" . 1.06 . "<br>";
echo $meal = "$" . ($mealCost + $mealTip + $mealTax) . "<br>";
?>
The error I receive when using it is:
A non-numeric value encountered -- at line 5
$0
It throws this error back three times, once for $mealCost, $mealTip, and $mealTax.
To my knowledge, I am using the correct symbol and syntax for addition, and PHP should be able to suss numbers from strings so adding the "$" shouldn't make a difference. I even experimented by removing the "$", and it threw back the same error, the only difference being that instead of returning a $0 sum after the errors, it returned the correct sum.
I'm not sure what steps I need to take to force PHP to see these numbers as actual numbers. I've used all the commands I learned thus far with no good results, and an hour of research here and on the net is not turning up anything I can use.
Upvotes: 0
Views: 400
Reputation: 25725
You are converting all the variables to strings. Once this happens, you cannot do numerical addition to them.
See for example:
"$" . 16.25 . "<br>"
This becomes a string with a $ and a linefeed at the end.
Try this, in which I do the assignment inside ()
but I also output the intermediate numbers of the bill. Finally, the total is at the bottom - as the OP seems to intend.
<?php
echo "$" . ($mealCost = 16.25) . "<br>";
echo "$" . ($mealTip = 3.25) . "<br>";
echo "$" . ($mealTax = 1.06 ) . "<br>";
echo $meal = "$" . ($mealCost + $mealTip + $mealTax) . "<br>";
?>
$16.25<br>$3.25<br>$1.06<br>$20.56<br>
Live Example: Fiddle/PhpSandbox
Upvotes: 1
Reputation:
When you concatenate integers with strings, they become strings. That's why you get this error when you are trying to make arithmetic operations on them, because they are not integers anymore.
Try this:
<?php
echo $mealCost = 16.25;
echo $mealTip = 3.25;
echo $mealTax = 1.06;
echo $meal = "$" . ($mealCost + $mealTip + $mealTax) . "<br>";
?>
Upvotes: 1