5

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 ?

3 Answers 3

5

Try simply using array_map,count,& array_unique like as

array_map(function($v) {
            return count(array_unique($v));
        }, $arr);
Sign up to request clarification or add additional context in comments.

2 Comments

You cannot get a more elegant solution.
@Uchiha The alternatives? i guess the rest of the answers... but this is the most elegant one.
5

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

Comments

2

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.