Process a sequence of integer values to determine which values occur in the sequence and how many times each occurs.
<? // 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: 6, 6, 1, 5, 6, 6, 5, 2, 5, 8
- 1 occurs 1 time(s)
- 2 occurs 1 time(s)
- 5 occurs 3 time(s)
- 6 occurs 4 time(s)
- 8 occurs 1 time(s)