PHP frequency of array values in order

Display repetitive values as a list in frequency order

The values are in a text file containing various repeating strings, one per line, eg:

green bus
black car
red bus
blue truck
green bus
green bus
red bus

The object is to display them aggregated, with the most frequent item at the top, then downwards in frequency order with a running total, as follows:

1. green bus : 3 : 3
2. red bus : 2 : 5
3. black car : 1 : 6
4. blue truck : 1 : 7

It's quite simple to do.

<ol> <!-- Start ordered numerical HTML list -->
<?php // Start script

// Get text file into an array
$itemArray = file('textfile.txt');
// Return the array using its values as keys and their frequency as values
$listed = array_count_values($itemArray);
// Sort the array as numeric in reverse order maintaining index association
arsort($listed, SORT_NUMERIC);

$running = 0; // Initiate variable for running totals
// Loop through associative array to process it with $num as the frequency
foreach ($listed as $item => $num) {
  $item = str_replace("\n", "", trim($item)); // Strip newlines
  $running = $running + $num; // Add to running total
  echo '<li>' . $item . ' : ' . $num . ' : ' . $running . '</li>');
}

?>
</ol> <!-- End ordered numerical HTML list -->

It works (with hundreds of items).

Technical »

—   
Page last modified: 13 April, 2024
Search | Legal | Qwwwik
Patrick Taylor Art

Menu