PHP - count specific array values

前端 未结 10 1554
野的像风
野的像风 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 18:52

    Use array_count_values() function . Check this link http://php.net/manual/en/function.array-count-values.php

    0 讨论(0)
  • 2020-12-02 18:53
    $array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
    $counts = array_count_values($array);
    echo $counts['Ben'];
    
    0 讨论(0)
  • 2020-12-02 19:00
    define( 'SEARCH_STRING', 'Ben' );
    
    $myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
    
    $count = count(array_filter($myArray,function($value){return SEARCH_STRING === $value;}));
    
    echo $count, "\n";
    

    Output:

    3
    
    0 讨论(0)
  • 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%)!

    0 讨论(0)
提交回复
热议问题