Jump to content

Adding the values of strings containing numbers


mcfmullen

Recommended Posts

Alright, I'll admit it was stupid on my part but here goes:

 

I have a database set up with three fields each containing varchar values:

first, second, third.

 

For the sake of this example here is what one row would contain:

500: 750: 1,000

 

Admitedly, the fields should have been int fields but oh well, on to my dilemma:

 

In php I want to add up the total of these three fields. The fields are stored in an array and I am using this code to add them up:

 

<td width="14%"><?php $row['first'] + $row['second'] + $row['third']; ?></td>

 

I don't get any results because well, the values are string and not numbers.

 

Is there an easy way for me to add these values or am I going to have to go into the database, remove all the commas from any large values and reset the field as int instead of varchar?

You're not trying to do anything with the result, as in you aren't assigning the result to a variable, or echoing it, or anything.

 

Try <?php $total = ($row['first'] + $row['second'] + $row['third']); echo $total; ?>

So I've tried that an my results are:

 

first = 600

second = 1,200

third = 1,800

 

I get an answer of 602 which is obviously incorrect. Keep in mind that the value of 1,200 and 1,800 are in varchar thus are strings. $total isn't seeing past the commas. Is there any way around it?

You have to get rid of the commas. Numbers don't normally have commas in them except when they are printed in some countries.

 

<?php
$total = str_replace(',','',$row['first']) + str_replace(',','',$row['second']) + str_replace(',','',$row['third']));
echo number_format($total);
?>

 

Ken

 

EDIT: Ken beat me, but I typed it out, so I'm leaving it  :P

 

Yes, strreplace(). Assuming the only character other than numbers in the strings are commas:

 

<?php
$row['first'] = "1,200";
$row['second'] = "2,000";
$row['third'] = "3,000";

$first = str_replace(',', '', $row['first']);
$second = str_replace(',', '', $row['second']);
$third = str_replace(',', '', $row['third']);

$value = ($first + $second + $third);
echo $value; //RETURNS 6200
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.