Robson » Little Red Book » Occurence count

Chapter 7 - Question 9

Process a sequence of integer values to determine which values occur in the sequence and how many times each occurs.

Solution 1

<?
   // generate a random number of random numbers
   for ($n = 0; $n < mt_rand(5, 20); $n++)
       $sequence[] = mt_rand(1, 10);
       
   // count up the number of times each value occurs
   // place the results in an array
   $occurence = array_count_values($sequence);
   // sort and maintain keys
   ksort($occurence);
   
   // show the sequence and start a list
   echo 'Sequence: ' . implode(', ', $sequence) . '<ul>';
   
   // loop through each occurence
   foreach ($occurence as $value => $frequency)
       // show the value and the amount of times it's found in the sequence
       echo '<li>' . $value . ' occurs ' . $frequency . ' time(s)</li>';
       
   // end the list
   echo '</ul>';    
?>

Which produces:

Sequence: 8, 10, 5, 1, 3, 10, 8, 8, 5, 5
  • 1 occurs 1 time(s)
  • 3 occurs 1 time(s)
  • 5 occurs 3 time(s)
  • 8 occurs 3 time(s)
  • 10 occurs 2 time(s)

Log

© 2004-17 robson | cc unless stated