Deniz Zoeteman
Deniz Zoeteman

Reputation: 10111

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?

Upvotes: 2

Views: 148

Answers (7)

mickmackusa
mickmackusa

Reputation: 47894

If you prefer code brevity zero global scope pollution, you can count every value and access the one count that you do want:

echo array_count_values(array_merge(...$array))['Thing1'] ?? 0;

If you don't want to bother counting values where the count will never be needed, then you can visit leafnodes with array_walk_recursive() and +1 everytime the target value is encountered.

$thing1Count = 0;
array_walk_recursive($array, function($v) use(&$thing1Count) { $thing1Count += ($v === 'Thing1'); });
echo $thing1Count;

Both snippets return 2. Here's a Demo.

Upvotes: 0

Prasanth Bendra
Prasanth Bendra

Reputation: 32740

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'];

Upvotes: 2

Narek
Narek

Reputation: 3823

function showCount($arr, $needle, $count=0)
{
    // Check if $arr is array. Thx to Waygood
    if(!is_array($arr)) return false;

    foreach($arr as $k=>$v)
    {
        // if item is array do recursion
        if(is_array($v))
        {
            $count = showCount($v, $needle, $count);
        }
        elseif($v == $needle){
            $count++;
        }
    }
    return $count;  
}

Upvotes: 2

thumber nirmal
thumber nirmal

Reputation: 1617

try this

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

Upvotes: 1

Alvaro
Alvaro

Reputation: 41595

Using in_array can help:

$cont = 0;

//for each array inside the multidimensional one
foreach($multidimensional as $m){
    if(in_array('Thing1', $m)){
        $cont++;
    }
}

echo $cont;

For more info: http://php.net/manual/en/function.in-array.php

Upvotes: 1

mohammad mohsenipur
mohammad mohsenipur

Reputation: 3149

you can use array_search for more information see this http://www.php.net/manual/en/function.array-search.php

this code is sample of this that is in php document sample

<?php 
function recursiveArraySearchAll($haystack, $needle, $index = null) 
{ 
 $aIt     = new RecursiveArrayIterator($haystack); 
 $it    = new RecursiveIteratorIterator($aIt); 
 $resultkeys; 

 while($it->valid()) {        
 if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND (strpos($it->current(), $needle)!==false)) { //$it->current() == $needle 
 $resultkeys[]=$aIt->key(); //return $aIt->key(); 
 } 

 $it->next(); 
 } 
 return $resultkeys;  // return all finding in an array 

} ; 
?> 

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

http://www.php.net/manual/en/function.array-keys.php

Upvotes: 3

Barif
Barif

Reputation: 1552

$count = 0;

foreach($array as $key => $value)
{
if(in_array("Thing1", $value)) $count++;
}

Upvotes: 0

Related Questions