English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Given a value how do I find out how many of that value exists in an array?

These is a function to calculate duplicates, but I only want to count certain values.

2007-11-07 08:57:46 · 5 answers · asked by Tasm 6 in Computers & Internet Programming & Design

5 answers

You could create a simple function like this :

function findDuplicates($data,$dupval) {
$nb= 0;
foreach($data as $key => $val)
if ($val==$dupval) $nb++;
return $nb;
}

$ar = array(10,20,10,30,40,10);
echo findDuplicates($ar,10); //will echo '3'

Hope it helps. Regards

2007-11-07 13:27:32 · answer #1 · answered by acerb 2 · 0 0

Php Count Array

2016-10-06 03:04:30 · answer #2 · answered by ? 4 · 0 0

There is a function to count the number of every value in an array. For example if $input was the array 1, dog, 2, 2, dog, 2, 3, 3, 4, 5, dog, 2, 5 then:

$counts = function array_count_values($input) would return an array of:

$counts[1] = 1
$counts[2] = 4
$counts[3] = 2
$counts[4] = 1
$counts[5] = 2
$counts[dog] = 3

You could then do something like:

foreach($count as $key => $value){
echo 'the value '.$key.' occurs in the array '.$value.' times.';
}

2007-11-08 06:08:47 · answer #3 · answered by merlot7799 3 · 0 0

I surely have in no way programmed in C till now yet from my know-how of regularly occurring programming i might advise sorting the array alphabetically then stepping by way of each and each value of the array and comparing it to a stored variable of the previous value. in the event that they're diverse; placed the fee in a 2d array. in the event that they're the comparable pass directly to the subsequent value. Sorry if that's no longer useful in C.

2016-12-08 15:03:07 · answer #4 · answered by ? 4 · 0 0

I get what you mean. Use array_keys.

$array = array("a", "b", "a", "a", "d");
$keys = array_keys($array, "a");
echo count($keys);

Result: 3

2007-11-08 09:04:24 · answer #5 · answered by lawyers 3 · 0 0

fedest.com, questions and answers