2

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?

7 Answers 7

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

searches for and returns key (not keyS)
@Waygood 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.
I did read it. You need to use array_keys() NOT array_search()
No Probs,I'd already +1'd your answer anyway for 'walking' through the array
2

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

8 Comments

+1 for use array functions directly but i have one question how to get particular "thing1" count using this answer only.
$answers=array_count_values(call_user_func_array('array_merge', $arr)); echo $answers['Thing1']
the array_count_values works, but what if the first and second value in the array are the same? I don't want the 2nd value to count.
@gdscei : "what if the first and second value in the array are the same?" - which array do you mean resulting array ?
In resulting array it shows the occurance of a particular value, if value occurs two times, Eg: in question Thing1 occurs 2 times so resulting array shows $res['Thing1'] as 2
|
2
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;  
}

Comments

1

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

1 Comment

did you check output?...it's not working...have to use $cont++
1

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

Comments

0
$count = 0;

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

1 Comment

multi-dimension! use array_walk_recursive or array_map
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.