Answer the question
In order to leave comments, you need to log in
How to count the number of identical digits and sum them up?
Hello everyone, I can’t figure out how to sum up the number of identical digits in a line, for example, there is a line
7774455566
I do it like this.
$split = str_split(7774455566);
echo json_encode(array_icount_values($split));
function array_icount_values($array) {
$ret_array = array();
foreach($array as $value) {
foreach($ret_array as $key2 => $value2) {
if(strtolower($key2) == strtolower($value)) {
$ret_array[$key2]++;
continue 2;
}
}
$ret_array[$value] = 1;
}
return $ret_array;
}
{"7":3,"4":2,"5":3,"6":2}
Answer the question
In order to leave comments, you need to log in
1. Do not deceive people)) 7774455566 is not a string at all )
2. You don’t need json here at all.
3. Create an associative array where the keys are numbers, and the values are their number. Then sum up in another loop those values that are greater than 1.
4. If there may be extraneous characters in the string, remove them with a regular expressionpreg_replace('/[^\d]/', '', $inputString);
echo array_sum(array_filter(array_count_values(str_split('7774455566')), function($v) {return $v > 1;}));
More or less like this:
$result = [];
$number = 7774455566;
while ($number) {
$digit = $number % 10;
if (!isset($result[$digit]) {
$result[$digit] = 0;
}
$result[$digit]++;
$number = (int) ($number / 10);
}
$sum = 0;
foreach ($result as $digit => $occurencesCount) {
if ($occurencesCount > 1) {
$sum += $digit;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question