PHP - count specific array values

前端 未结 10 1553
野的像风
野的像风 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:34

    try the array_count_values() function

    <?php
    $array = array(1, "hello", 1, "world", "hello");
    print_r(array_count_values($array));
    ?>
    

    output:

    Array
    (
        [1] => 2
        [hello] => 2
        [world] => 1
    )
    

    http://php.net/manual/en/function.array-count-values.php

    0 讨论(0)
  • 2020-12-02 18:39

    You can do this with array_keys and count.

    $array = array("blue", "red", "green", "blue", "blue");
    echo count(array_keys($array, "blue"));
    

    Output:

    3
    
    0 讨论(0)
  • 2020-12-02 18:41

    In my case of two dimensional array, from PHP Official Page comments, I found the useful snippet for a two dimensional array-

    <?php
    
    $list = [
      ['id' => 1, 'userId' => 5],
      ['id' => 2, 'userId' => 5],
      ['id' => 3, 'userId' => 6],
    ];
    $userId = 5;
    
    echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2
    ?>
    
    0 讨论(0)
  • 2020-12-02 18:45

    If you want to count ALL the same occurences inside the array, here's a function to count them all, and return the results as a multi-dimensional array:

    function countSame($array) {
    
    $count = count($array);
    $storeArray = array();
    while ($count > 0) {
    $count--;
    
    if ($array[$count]) {
    $a = $array[$count];
    $counts = array_count_values($array);
    $counts = $counts[$a];
    $tempArray = array($a, $counts);
    array_push($storeArray, $tempArray);
    
    $keys = array_keys($array, $a);
    foreach ($keys as $k) {
    unset($array[$k]);
    } //end of foreach ($keys as $k)
    } //end of if ($array[$count])
    
    } //end of while ($count > 0)
    
    return $storeArray;
    
    } //end of function countSame($array)
    
    0 讨论(0)
  • 2020-12-02 18:46

    Try the PHP function array_count_values.

    0 讨论(0)
  • 2020-12-02 18:52

    Use the array_count_values function.

    $countValues = array_count_values($myArray);

    echo $countValues["Ben"];

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