Reputation: 151
my code:
foreach($comment as $key => $value) {
$total = $value['likes'];
echo "$key: $total\n"
}
Outputs:
0: 3 1: 18 2: 72 3: 0 4: 10 5: 0 6: 0 7: 0 8: 0 9: 0 10: 0 11: 19 12: 0 13: 0 14: 14 15: 19 16: 0 17: 0 18: 1
How do I sum all the values? The array_sum
function gives a "warning: expects parameter 1 to be array, integer given".
Upvotes: 1
Views: 2249
Reputation: 3418
Array_sum is expecting a single dimension array. From the looks of your code you have a multi-dimensional array. Where $value is an array too.
You have the right idea with the total, but you have to add to your total like this $total = $total + $value['likes']
, or the shorthanded version $total += $value['likes']
:
$total = 0;
foreach($comment as $key => $value) {
$total += $value['likes'];
echo "$key: $total\n"
}
echo "My total is: $total";
Upvotes: 1
Reputation: 2275
$sum = 0;
foreach($comment as $key=>$value) {
$sum+=$value;
}
echo "Total: $sum";
Upvotes: 1
Reputation: 21466
Keep a running total...
$total_likes = 0;
foreach($comment as $key => $value) {
$total = $value['likes'];
$total_likes += $total;
echo "$key: $total\n"
}
echo "Total: $total_likes \n";
Upvotes: 0
Reputation: 6355
You need to start off with a variable and keep adding to it if you want to do it this way.
$total = 0;
foreach($comment as $key => $value) {
$total += $value['likes'];
}
echo "The sum is: " . $total;
Upvotes: 1