Jump to content

Count multiple values in an array


satikas
Go to solution Solved by Barand,

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
Share on other sites

use the examples you found to count the ones and then to count the twos and add the two results.

$number_of_ones_and_twos=$ones+$twos;

if you try it and have trouble, post your code and we'll help.

Edited by davidannis
Link to comment
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; ?>
Edited by satikas
Link to comment
Share on other sites

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; ?>
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.