greenbandit
greenbandit

Reputation: 2275

Count occurrences of unique values from a flat array

I need to count the occurrences of all of the unique values from my array. Here is an example of it:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 1
    [4] => 4
    [5] => 6
    [6] => 6
)

I'm looking for a way to sum all from same value:

Array
(
    [1] => 4
    [4] => 1
    [6] => 2
)

Upvotes: 0

Views: 15658

Answers (4)

Cheery
Cheery

Reputation: 16214

RTM: http://www.php.net/array_count_values

ps: assuming that "[5] => 5" is a typo. Otherwise explain more carefully.

Upvotes: 4

Siddharth Shukla
Siddharth Shukla

Reputation: 1131

 **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);

Upvotes: 0

Sam Arul Raj T
Sam Arul Raj T

Reputation: 1770

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);

Upvotes: 0

Sabari
Sabari

Reputation: 6335

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);

Upvotes: 4

Related Questions