Search code examples
phparraysmultidimensional-arraycounting

Count occurrences of a specific value in multidimensional array


Let's say I have a multidimensional array like this:

[
    ["Thing1", "OtherThing1"],
    ["Thing1", "OtherThing2"],
    ["Thing2", "OtherThing3"]
]

How would I be able to count how many times the value "Thing1" occurs in the multidimensional array?


Solution

  • Try this :

    $arr =array(
    array("Thing1","OtherThing1"),
    array("Thing1","OtherThing2"),
    array("Thing2","OtherThing3")
    );
    
    echo "<pre>";
    $res  = array_count_values(call_user_func_array('array_merge', $arr));
    
    echo $res['Thing1'];
    

    Output :

    Array
    (
        [Thing1] => 2
        [OtherThing1] => 1
        [OtherThing2] => 1
        [Thing2] => 1
        [OtherThing3] => 1
    )
    

    It gives the occurrence of each value. ie : Thing1 occurs 2 times.

    EDIT : As per OP's comment : "Which array do you mean resulting array?" - The input array. So for example this would be the input array: array(array(1,1),array(2,1),array(3,2)) , I only want it to count the first values (1,2,3) not the second values (1,1,2) – gdscei 7 mins ago

    $arr =array(
    array("Thing1","OtherThing1"),
    array("Thing1","OtherThing2"),
    array("Thing2","OtherThing3")
    );
    
    $res  = array_count_values(array_map(function($a){return $a[0];}, $arr));
    
    echo $res['Thing1'];