How do I count occurrence of duplicate items in array

前端 未结 12 1306
我寻月下人不归
我寻月下人不归 2020-11-27 03:32

I would like to count the occurrence of each duplicate item in an array and end up with an array of only unique/non duplicate items with their respective occurrences.

<
12条回答
  •  旧巷少年郎
    2020-11-27 04:12

        $input = [1,2,1,3,2,4,10];
        //if give string
        //$input = "hello hello how are you how hello";
        //$array = explode(' ',$input);
        $count_val = [];
        foreach($array as $val){
          $count_val[$val]++;
        }
        print_r($count_val);
    //output ( [1] => 2 [2] => 2 [3] => 1 [4] => 1 [10] => 1 )
    

提交回复
热议问题