tags:

views:

37

answers:

2

Let's say $_SESSION['totalprice'] is 1200. However echo $totalprice; outputs 1200 and echo $grandtotal; outputs 66. Grandtotal should be 1265.

What am I doing wrong here?

$totalprice = $_SESSION['totalprice'];
$shipping= 65;

if (count($_SESSION['cart'])){
 $count = 1;
 foreach ($_SESSION['cart'] as $PID => $row){ 
  echo "<p class='padnmgn'><b>". $row['count'] . " " . $row['name'] . " @ " . $row['price']."</b></p><br/>\n";
  echo "<input type='hidden' name='item_name_".$count."' value='".$row['name']."'/>\n";
  echo "<input type='hidden' name='item_quantity_".$count."' value='".$row['count']."'/>\n";
  echo "<input type='hidden' name='item_price_".$count."' value='".$row['price']."'/>\n";
  echo "<input type='hidden' name='item_currency_".$count."' value='NOK'/>\n";
  echo "<input type='hidden' name='ship_method_name_".$count."' value='Posten'/>\n";
  echo "<input type='hidden' name='ship_method_price_".$count."' value='65.00'/>\n";

 }
}
$grandtotal = $totalprice + $shipping;

echo $totalprice;
echo $grandtotal;
+1  A: 

Try this:

$grandtotal = ((int) $totalprice) + $shipping;
Sarfraz
It still outputs 66.
shin
@shin: then most likely your values of total gets changed in the session by some code somewhere.
Sarfraz
OK, I will check it. thanks.
shin
A: 

Are you sure the value inside $totalprice is actually an integer and are you sure it's not being modified before you get to the addition? Try doing var_dump($totalprice); just before you do the addition, to see what value it really has at that point.

If it does have the value you expect, then you may need to cast it to an integer explicitly for the calculation to work properly, so something like (int)$totalprice + $shipping; etc.

For example,

<?php
    $totalprice = "1200blahblah";
    $shipping = 65;
    $grandtotal = (int)$totalprice + $shipping;
    echo $grandtotal; // still prints "1265"
?>
Rich Adams
It shows as string: string(8) "1,072.00". However if I use $newtotalprice = (int)$totalprice;var_dump($newtotalprice); It shows int(1), nothing else.
shin
The output is 1,(comma)072.(dot)00. Is it the cause of problem?
shin
Yes, that is your problem. PHP is trying to convert the string to an integer, and so it's just taking the "1" before it hits the "," character (since it can't convert "," to a number). Which is why it's doing 65+1=66. You need to remove the formatting from the string so that it's just the numbers you want. This will remove the "," characters: $totalprice = str_replace(',','',$totalprice); Then (int)$totalprice will give you the right value.
Rich Adams
Although since you're dealing with prices, you probably want to work with floats and not ints. Also you probably shouldn't be formatting the number until you're ready to output it, otherwise it makes doing calculations more prone to errors, just like you were getting.
Rich Adams