I got a String like this:
,10,10,10,10,10,10,10,11
How can I count how many different numbers are there?
I got a String like this:
,10,10,10,10,10,10,10,11
How can I count how many different numbers are there?
//remove the starting from the given string,
$input = substr($input, strpos(',', $input) + 1);
//split the string on ',' and put it in an array
$numbers = explode(',', $input);
//an array to put our unique numbers in
$counter = array();
//for each number
foreach($numbers as $number) {
//check if it is not in the unique 'counter' array
if(!in_array($number, $counter)) {
//remember this unique number
$counter[] = $number;
}
}
//count the unique number array
$different = count($counter);
//give some output
echo "There are " . $different . " unique numbers in the given string";
the input variable should be your text, because your text starts with a ',' we strip it out of our input string
You can use the explode function for making the string
an array then use array_unique
function on it for getting the unique number's of it. From this array array you can easily count how many of your number unique.
$str = ",10,10,10,10,10,10,10,11";
$arr = explode(",", trim($str, ","));
$arr = array_unique($arr);
print_r($arr);
Result:
Array
(
[0] => 10
[7] => 11
)
so now its time to count, just use count
.
echo count($arr);// 2
explode
the string
on ,
array_filter
without callback, to remove empty matches (first comma)array_unique
to remove dup valuescount
to return the size of array_unique
$string = ",10,10,10,10,10,10,10,11";
echo count(array_unique(array_filter(explode(",", $string))));
Try something like this :
$string = '10, 10, 11, 11, 11, 12';
$numbers = explode(',',$string);
$counter = array();
foreach($numbers as $num) {
$num = trim($num);
if (!empty($num)) {
if (!isset($counter[$num])) {
$counter[$num]=1;
} else {
$counter[$num]++;
}
}
}
print_r($counter);
Hope this help!