A
A
Artur Yalaltdinov2016-06-28 12:09:55
PHP
Artur Yalaltdinov, 2016-06-28 12:09:55

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;
    }

it returns me
{"7":3,"4":2,"5":3,"6":2}
How do I sum up only those numbers where there are match values ​​> 1, that is, 3+2+3+2?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
index0h, 2016-06-28
@index0h

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 expression
preg_replace('/[^\d]/', '', $inputString);

S
SharuPoNemnogu, 2016-06-28
@SharuPoNemnogu

echo array_sum(array_filter(array_count_values(str_split('7774455566')), function($v) {return $v > 1;}));

G
Grigory Esin, 2016-06-28
@xotey83

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 question

Ask a Question

731 491 924 answers to any question