Yousef Altaf Yousef Altaf - 6 months ago 18
PHP Question

array_sum return raw numbers without sum - php

I am using Array_sum like this

<?php
$totalAmount = $db->prepare('SELECT
a.proId, a.userId,
b.id, b.pPrice
FROM purchaseshistory AS a
INNER JOIN products AS b ON(a.proId=b.id)
WHERE a.userId=?');
$totalAmount->bind_param('i', $cus['cId']);
$totalAmount->execute();
$totalAmount->bind_result($proId, $userId, $id, $pPrice);
$totalAmount->store_result();
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
$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);
Comments