Array_sum returns the value 0

I wrote this php code:

$query="SELECT post_hit FROM posts WHERE MONTH(post_date)=11 AND YEAR(post_date)=2016 AND post_hit>0 ";
        $select_query= mysqli_query($connect, $query);
        $post_hit= mysqli_fetch_all($select_query);
        echo array_sum($post_hit);

and the var dump result is the following:

array (size=6)
0 =>
array (size=1)
0 => string ‘8’ (length=1)
1 =>
array (size=1)
0 => string ‘9’ (length=1)
2 =>
array (size=1)
0 => string ‘1’ (length=1)
3 =>
array (size=1)
0 => string ‘3’ (length=1)
4 =>
array (size=1)
0 => string ‘10’ (length=2)
5 =>
array (size=1)
0 => string ‘64’ (length=2)

The problem is that the “echo array_sum($post_hit);” returns me the value of 0.What am i going wrong? I need to get the values from a specific column in my database and then to sum all these values.

$post_hit is an array of arrays

It should work better if you do a foreach loop to assign each nested array value to a new array and then sum that. Or you could do the addition in the loop if you prefer.

1 Like

there’s no need to use PHP for this summation. SQL can do that for you much better.


Good catch, I totally missed that - so into a PHP mindset at the time that I didn’t think of SUM().

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.