PHP - count specific array values

前端 未结 10 1575
野的像风
野的像风 2020-12-02 18:00

How can I count the number of element inside an array with value equals a constant? example,

$myArray = array(\"Kyle\",\"Ben\",\"Sue\",\"Phil\",\"Ben\",\"Mar         


        
10条回答
  •  悲哀的现实
    2020-12-02 19:00

    array_count_values only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:

    function arrayCountValues($arr) {
      $vals = [];
      foreach ($arr as $val) { array_push($vals,strval($val)); }
      $cnts = array_count_values($vals);
      arsort($cnts);
      return $cnts;
    }
    

    Note that I return $cnts with the keys as strings. It would be easy to reconvert them, but I'm trying to determine the mode for the values, so I only need to re-convert the first (several) values.

    I tested a version which looped, creating an array of counts rather than using array_count_values, and this turned out to be more efficient (by maybe 8-10%)!

提交回复
热议问题