I need to sum all the values from my array, so here is an example of it:
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 4
[5] => 6
[6] => 6
)
looking a way to sum all from same value:
Array
(
[1] => 4
[4] => 1
[6] => 2
)
Any ideas?
RTM: http://www.php.net/array_count_values
ps: assuming that "[5] => 5" is a typo. Otherwise explain more carefully.
If you want to add all the values in an array then you can use :
$test = array(1,1,1,1,4,6,6);
$test_sum = array_sum($test);
If you want to count the number of occurrences of each value in the array then you can use:
$test = array(1,1,1,1,4,6,6);
$test_count = array_count_values($test);
This will result the sum for the array dude
$array =array
(
1 => 4,
4 => 1,
5 => 5,
6 => 2
);
$sum =0;
foreach ($array as $k=>$v):
$sum = $sum+$v;
endforeach;
echo $sum;
second answer This could be more easy
echo array_sum($array);
**Sum of array without any function we can get.**
<?php
$array =Array(1,1,1,1,4,6,6);
$add =0;
for($i =0;$i<count($array);$i++){
$add = $add+$array[$i];
}
echo $add;
?>
**predefined function using**
$array =Array(1,1,1,1,4,6,6);
echo array_sum($array);