A little bit of array manipulation can greatly simplify this:
$counts = array_fill(1, 5, 0);
$labels = array(1 => 'one', 'two', 'three', 'four', 'five');
while(...) {
$index = array_search(get_post_meta($post->ID, 'rate', true), $labels);
$counts[$index] += $index;
}
The totals are kept inside $counts
, with $counts[1]
being the total of ones. $labels
is there to help match the textual representation with the array positions inside $counts
-- this could of course be done with a plain switch
instead.
The loop uses array_search
to convert textual representations to array indexes, then simply increments the corresponding count by an amount equal to the index.
Production code should of course also account for the possibility of array_search
returning false
.