Jump to content

Count multiple values in an array


satikas

Recommended Posts

Hey,

there are many guides on the internet that show how to count the occurance of a value in an array.

for example count how many 2`s are in an array 1,2,2,3, its: 2

 

However I couldnt find how to count multiple values, like how many 1`s and 2`s together are in 1,2,2,3, its: 3.

 

Thanks for any help!

Link to comment
https://forums.phpfreaks.com/topic/278412-count-multiple-values-in-an-array/
Share on other sites

That would be simple and usable, but unfortunately I dont know the number of values im checking in another array.
In other words if one array was: 1, 1, 2, 3, 3, 4, 5, 5, 6, 4, 8, 9 then im checking for 1s and 2s, sometimes 2s and 5s and 6s. and so on.

 

So basically my code has 2 arrays. 1 is the main one and the other one contains the numbers that should be checked in the first one and their occurances should be added.

 

I was thinking that maybe I need 2 foreach loops for this? My head is really heavy :happy-04:

<?php $array_1 = array("1","2","2","3");
$array_2 = array("1","2"); //count how many 1s ands 2s are in total

$counts = array_count_values($array_1);

$count = 0;
foreach($array_1 as $array_1_value){
	foreach($array_2 as $array_2_value){
		$count = $counts[$array_2_value];
	}
}

echo $count; ?>

Tried to modify and make it more logical with in_array, however instead of 3 it prints me 8:

<?php $array_1 = array("1","2","2","3");
$array_2 = array("1","2"); //count how many 1s ands 2s are in total

$count = 0;
foreach($array_1 as $array_1_value){
	foreach($array_2 as $array_2_value){
		if (in_array($array_2_value, $array_1)){
			$count += 1;
		}
	}
}

echo $count; ?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.