- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘Back End’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
I’m storing values in an array like so.
$holder = array(
“1” => “100.12”,
“2”=> “232.45”,
“3”=> “459.18”
);
I have multiple arrays like this that I need to add to a $total variable. Can I add currency like this or do I need to do it differently.
I have multiple arrays like this that I need to add to a $total variable.
Meaning, you want to total all values in all of your arrays? or you want to total each index in all of your arrays?
Can I add currency like this or do I need to do it differently.
Differently.
Your values are defined as strings, not as numbers.
They have decimal points in them, so when you start doing math on them, they’ll be converted to floatsâ€¦ which is the single worst data type to do decimal math (see the “floating-point precision” warning here).
Now, especially when dealing with money, there is an expectation that your arithmetic will be correct. They safest way to ensure this is to make sure you use integers: multiply all values by 100 and do your math on cents instead of dollars. If you’re doing multiplication or division (e.g., calculating percentages or averages) where you need greater precision, you might want to use a bigger factor.
To get you started:
$data = [
"1" => 10012,
"2" => 23245,
"3" => 49518
];
function bling_bling($cents){
return $cents / 100;
}
echo "$ " . bling_bling(array_sum($data));
Just make sure array values are numeric like @traq said and use cents.
To explain my earlier question, take these arrays as an example:
$a1 = [
1 => 100,
2 => 200,
3 => 300
];
$a2 = [
1 => 101,
2 => 102,
3 => 103
];
Which is the result you are looking for?
$r1 = [
1 => 201,
2 => 302,
3 => 403
];
$r2 = [
1 => 500,
2 => 305
];
$r3 = 805;