
Wikis & learning
Sort counts without losing their labels
If a category name is stored as the array key, a sort that discards keys can separate each count from the label it describes. Choose a sorting operation that preserves that association.
If a category name is stored as the array key, a sort that discards keys can separate each count from the label it describes. Choose a sorting operation that preserves that association.
Walkthrough
arsort orders the counts from largest to smallest while retaining their keys. The example then walks through both the label and its associated count.
PHP example
<?php
$counts = ['notes' => 2, 'guides' => 7, 'tools' => 4];
arsort($counts);
foreach ($counts as $label => $count) {
echo $label, ': ', $count, PHP_EOL;
}Expected output
guides: 7
tools: 4
notes: 2Change and check
Add another category with a different count. Try ksort to see how ordering by label changes the display while the associations stay intact.
Discussion
Sign in to participate.



