Yousef Altaf Yousef Altaf - 1 year ago 82
PHP Question

array_sum return raw numbers without sum - php

I am using Array_sum like this

$totalAmount = $db->prepare('SELECT
a.proId, a.userId,, b.pPrice
FROM purchaseshistory AS a
INNER JOIN products AS b ON(
WHERE a.userId=?');
$totalAmount->bind_param('i', $cus['cId']);
$totalAmount->bind_result($proId, $userId, $id, $pPrice);
while ($totalAmount->fetch()) {
$sum = 0;
$amount = $pPrice;
$amount = is_array($amount) ? $amount : array($amount);
foreach ($amount as $item => $value) {
$sum += $value;
print $sum;

and also tried to make it like this

while ($totalAmount->fetch()) {
$amount = array($pPrice);
print array_sum($amount) ;

same results I get the numbers like 200150200

Answer Source
$amount = [];
while ($totalAmount->fetch()) {
       $amount[] = $pPrice;
echo array_sum($amount);

You're not adding elements to an array.. the code above is and should work as you expect

Update for older PHP versions

$amount = array();
while ($totalAmount->fetch()) {
       $amount[] = $pPrice;
echo array_sum($amount);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download