-3

So assuming I have this string 198419489151085175 and I want to get the most frequent number appearing on this string, how can I achieve this in PHP? What about the second most frequent?

Thanks in advance.

1 Answers1

0

You can do it in four steps:

  1. Use str_split() to create array from string which contains single digits.

  2. Use array_count_values() on this splitted string. It returns array which indexes are your digits and values are count of occurences of this digits.

  3. Use arsort() to sort array.

  4. Get first element of array using reset() and key() functions.

Example:

<?php

$string = '198419489151085175';

$splittedString = str_split($string);
$charactersCount = array_count_values($splittedString);
arsort($charactersCount);

reset($charactersCount);
$firstKey = key($charactersCount);

var_dump($charactersCount);
var_dump($firstKey);

And result is:

array(7) {
  [1]=>
  int(5)
  [9]=>
  int(3)
  [8]=>
  int(3)
  [5]=>
  int(3)
  [4]=>
  int(2)
  [0]=>
  int(1)
  [7]=>
  int(1)
}

1 // this is your result
Community
  • 1
  • 1
aslawin
  • 1,981
  • 16
  • 22