Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the array values with key

Tags:

arrays

php

I have array like this i need to count by array values

Array ( [Cop] => Array ( [0] => Dozen [1] => Dozen [2] => Akls [3] => Akls ) [MSN] => Array ( [0] => Dozen ) [NeK] => Array ( [0] => Suhan [1] => Ebao ) [NetSE] => Array ( [0] => SuZhan [1] => Guhang ) )

For example

 Array ( [Cop] => Array ( [0] => Dozen [1] => Dozen [2] => Akls [3] => Akls ))

In the Cop key i have two different values for cop so i need cop should be 2

Cop - 2
MSn - 1
NeK - 2 
NetSE - 2

I need the count like above how can i do this ?

like image 431
Question User Avatar asked Nov 06 '15 10:11

Question User


3 Answers

Try simply using array_map,count,& array_unique like as

array_map(function($v) {
            return count(array_unique($v));
        }, $arr);
like image 152
Narendrasingh Sisodia Avatar answered Oct 17 '22 08:10

Narendrasingh Sisodia


Use array_unique() and then count.

count(array_unique($array['Cop']));// output 2

If you want to print for every key do following:

$array = array('Cop'=>array('Dozen','Dozen','Akls','Akls'), 'MSN'=> array('Dozen'), 'NeK'=> array('Suhan','Ebao'));
foreach($array as $key => &$value) {
    $value = count(array_unique($array[$key]));
}
print_r($array);

Output:

Cop = 2
MSN = 1
NeK = 2
like image 45
Manwal Avatar answered Oct 17 '22 10:10

Manwal


You should use array_count_values() for that, here's an example:

$data = array('cop' => array(0 => 'test', 1 => 'test', 2 => 'test2'));

foreach($data as $item){
    $result = array_count_values($item);
    print_r($result);
}

Outputs:

Array
(
    [test] => 2
    [test2] => 1
)
like image 2
Stas Parshin Avatar answered Oct 17 '22 08:10

Stas Parshin